Last active
November 29, 2023 10:27
-
-
Save NishiGaba/c0b1416ab6215f2592034cc66aaf0d86 to your computer and use it in GitHub Desktop.
8 Methods to Iterate through Array
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
//8 Methods to Iterate through Array | |
//forEach (Do Operation for Each Item in the Array) | |
[1,2,3].forEach(function(item,index) { | |
console.log('item:',item,'index:',index); | |
}); | |
//map (Translate/Map all Elements in an Array to Another Set of Values.) | |
const oneArray = [1,2,3]; | |
const doubledArray = oneArray.map(function(item) { | |
return item*2; | |
}); | |
console.log(doubledArray); | |
//filter (Remove Unwanted Elements based on a Condition) | |
const intArray = [1,2,3]; | |
const rootArray = intArray.filter(function(item) { | |
return item % 2 === 0 ; | |
}); | |
console.log(rootArray); | |
//reduce (Gives Concatenated Value based on Elements across the Array) | |
const sum = [1,2,3].reduce(function(result,item) { | |
return result + item; | |
}, 0); | |
console.log(sum); | |
//some (If Any Item in the Entire Array Matches the Condition, it returns True) | |
const hasNegativeNum = [1,2,3,-1,5].some(function(item) { | |
return item < 0 ; | |
}); | |
console.log(hasNegativeNum); | |
//every (If All Items Matches the Condition,it returns True else False) | |
const allPositiveNum = [1,2,3].every(function(item) { | |
return item > 0; | |
}); | |
console.log(allPositiveNum); | |
//find (If Item Matches the Condition,it Returns that Item of the Array else Return Undefined) | |
const objects = [{id: 'a'},{id: 'b'},{id: 'c'}]; | |
const found = objects.find(function(item) { | |
return item.id === 'b'; | |
}); | |
console.log(found); | |
//find index (If Item Matches the Condition,it Returns the Index of that Item) | |
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
Nice, well done! π