Skip to content

Instantly share code, notes, and snippets.

@NishiGaba
Last active November 29, 2023 10:27
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save NishiGaba/c0b1416ab6215f2592034cc66aaf0d86 to your computer and use it in GitHub Desktop.
Save NishiGaba/c0b1416ab6215f2592034cc66aaf0d86 to your computer and use it in GitHub Desktop.
8 Methods to Iterate through Array
//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);
@krillo
Copy link

krillo commented Feb 16, 2022

Nice, well done! 😃

@davvvvsss
Copy link

Very helpful. Thanks.

@NishiGaba
Copy link
Author

Thanks @krillo 😇

@NishiGaba
Copy link
Author

Thanks @davvvvsss 😇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment