Created
March 14, 2016 16:26
-
-
Save mweibel/dcdd54af186181c7c531 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
]; |
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
one idea:
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.