Created
January 9, 2019 19:36
-
-
Save eewee/8bdc2b520b2475a87f319a3c4ac85fa0 to your computer and use it in GitHub Desktop.
Array iteration - 8 methods
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
//forEach | |
[1,2,3].forEach(function(item, index){ | |
console.log(item, index) | |
}) | |
//map | |
const three = [1,2,3] | |
const doubled = three.map(function(item){ | |
return item * 2 | |
}) | |
console.log(doubled) | |
//filter | |
const ints = [1,2,3] | |
const evens = ints.filter(function(item){ | |
return item % 2 === 0 | |
}) | |
console.log(evens) | |
//reduce | |
const sum = [1,2,3].reduce(function(result, item){ | |
return result + item | |
}) | |
console.log(sum) | |
//some | |
const hasNegativeNumbers = [1,2,3,-1,4].some(function(item){ | |
return item < 0 | |
}) | |
console.log(hasNegativeNumbers) | |
//every | |
const allPositiveNumbers = [1,2,3].every(function(item){ | |
return item > 0 | |
}) | |
console.log(allPositiveNumbers) | |
//find | |
const objects = [{id: 'a'}, {id: 'b'}, {id: 'c'}] | |
const found = objects.find(function(item){ | |
return item.id === 'b' | |
}) | |
console.log(found) | |
//find index | |
const objects2 = [{id: 'a'}, {id: 'b'}, {id: 'c'}] | |
const foundIndex = objects2.findIndex(function(item){ | |
return item.id === 'b' | |
}) | |
console.log(foundIndex) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment