Created
December 12, 2017 11:18
-
-
Save mansouryaacoubi/c18575ef40848cb9f7b0c27f7f8041a1 to your computer and use it in GitHub Desktop.
Different version to search in Array in Javascript
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
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