Skip to content

Instantly share code, notes, and snippets.

@mansouryaacoubi
Created December 12, 2017 11:18
Show Gist options
  • Save mansouryaacoubi/c18575ef40848cb9f7b0c27f7f8041a1 to your computer and use it in GitHub Desktop.
Save mansouryaacoubi/c18575ef40848cb9f7b0c27f7f8041a1 to your computer and use it in GitHub Desktop.
Different version to search in Array in Javascript
let categories = [{id: 1, name: 'EM'},{id: 2, name: 'EW'}, {id: 3, name: 'U15M'}, {id: 4, name: 'U15W'}];
let cat = null;
let selected = 3;
// VERSION 1: Use foreach-loop
for(var i in categories) {
cat = categories[i];
if(cat.id == selected) {
break;
}
}
// VERSION 2: Use find-function and anonymous function
cat = categories.find(function (c) {
return c.id == selected;
});
// VERSION 3: Use find-function and lambda function
cat = categories.find(c => c.id == selected);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment