Last active
October 22, 2019 03:05
-
-
Save michaelmcshinsky/d98727df866283be6e7c97dbe493f3f8 to your computer and use it in GitHub Desktop.
finding-objects-and-values-in-arrays-part-2
This file contains 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 arr = [ | |
{id: 1, name: 'Adam'}, | |
{id: 2, name: 'Bell'}, | |
{id: 3, name: 'Cody'}, | |
{id: 4, name: 'Dawn'} | |
]; |
This file contains 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 arr = [{id: 1, name: 'Adam'},{id: 2, name: 'Bell'},{id: 3, name: 'Cody'}], | |
value = 2; | |
// Array.find() | |
let result = arr.find(x => x.id === value); // 1 | |
console.log('result', result); // {id: 2, name: 'Bell'} | |
// Array.findIndex() | |
let index = arr.findIndex(x => x.id === value); // 1 | |
console.log('arr[index]', arr[index]); // {id: 2, name: 'Bell'} | |
// for - v.1 | |
let result1 = null; | |
for(let i = 0; i < arr.length; i++) { | |
if(arr[i].id === value) { | |
result1 = arr[i]; | |
break; // We are looking for the first occurrence of the object; | |
}; | |
}; | |
console.log('result1', result1); // {id: 2, name: 'Bell'} | |
// for - v.2 | |
let result2 = null; | |
for (let val of arr) { | |
if(val.id === value) { | |
result2 = val; | |
} | |
} | |
console.log('result2', result2); // {id: 2, name: 'Bell'} | |
// while | |
let result3 = null, | |
j = 0; | |
while (j < arr.length) { | |
if (arr[j].id === value) { | |
result3 = arr[j]; | |
break; | |
} | |
j++; | |
} | |
console.log('result3', result3); // {id: 2, name: 'Bell'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment