Skip to content

Instantly share code, notes, and snippets.

@mweibel
Created March 14, 2016 16:26
Show Gist options
  • Save mweibel/dcdd54af186181c7c531 to your computer and use it in GitHub Desktop.
Save mweibel/dcdd54af186181c7c531 to your computer and use it in GitHub Desktop.
var items = [
{
id: '1',
refId: 'A'
},
{
id: '2',
refId: 'B'
},
{
id: '1',
refId: 'C'
}
];
var refs = fetch(items.map(function(item) {
return item.refId;
})));
// refs after fetching, e.g.:
var refsAfter = [
'A',
'C'
];
// goal array, how to achieve best?
var itemsGoal = [
{
id: '1',
refId: 'A',
ref: true
},
{
id: '2',
refId: 'B',
ref: false
},
{
id: '3',
refId: 'C',
ref: true
}
];
@mweibel
Copy link
Author

mweibel commented Mar 14, 2016

one idea:

itemsGoal = items.map(function(item) {
  item.ref = refsAfter.some(functon(ref) {
    return ref === item.refId;
  });
  return item;
});

this is pretty simple, but has the drawback that we need to iterate over the full refsAfter array multiple times, O(n) I guess. For small amounts of data that's ok, but maybe there's a better way?

// Edit: ok with indexOf should be easier, initially had the idea that refs is an array of objects instead of objects.. which is not the case.

itemsGoal = items.map(function(item) {
  item.ref = refsAfter.indexOf(item.refId) !== -1;
  return item;
});

@swissmanu
Copy link

what about this in-place solution? it has no nested loops and runs with O(n).
it has the constraints that items and refsAfter are sorted by refId and refId is unique.

var items = [
  { id: '1', refId: 'A' },
  { id: '2', refId: 'B' },
  { id: '1', refId: 'C' },
  { id: '1', refId: 'D' }
];
var refsAfter = ['A','C'];

markRefs(items, refsAfter);
console.log(items);

function markRefs(items, refsAfter) {
  var i = 0;
  var j = 0;
  var countRefsAfter = refsAfter.length;
  while(i < countRefsAfter) {
    items[j].ref = (refsAfter[i] === items[j].refId)
    if (items[j].ref) {
      i++;
      j++;
    } else {
      j++;
    }
  }

  for(; j < items.length; j++) {
    items[j].ref = false;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment