Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fitsum/6452fb5b2faac4525263 to your computer and use it in GitHub Desktop.
Save fitsum/6452fb5b2faac4525263 to your computer and use it in GitHub Desktop.
check if obj exists in array then add if not
var source = [{name: "Fitsum", race: "blk"},{name: "Alice", race: "wht"},{name: "Jen", race: "wht"},{name: "Kim", race: "blk"},{name: "Lee", race: "asn"}],
target = [];
function userExists(name, idx, oldArr) {
return target.some(function(el) {
return el.name === name;
});
}
function addUser(name, idx, newArr) {
if (userExists(name, idx, source)) {
console.log(name,"already exists in", newArr);
return false;
}
target.push(source[idx]);
return true;
}
for(var i = 0; i < source.length; i++){
addUser(source[i].name, i, target);
}
console.log(target);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment