Last active
October 29, 2024 19:57
-
-
Save jasdeepkhalsa/32ae5c52765d283ddb67bb74c30d8283 to your computer and use it in GitHub Desktop.
Array Methods in JavaScript: Filter, Map, Reduce
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
var data = ['apple', 'pear', 'orange', 'orange', 'apple', 'lime', 'lime']; | |
data | |
.filter((item, index, array) => item !== 'pear') /* Let's filter out all pears (as they are horrible!) */ | |
.reduce((total, item, index, array) => { | |
if (total.indexOf(item) === -1) total.push(item); // Only add unique items to the array (de-duplication) | |
return total; // Return the cumulative total | |
}, [] /* Initial value, can be any primitive e.g. [], boolean etc */) | |
.map((item, index, array) => item + ' juice') /* Add the word 'juice' to the end */ | |
.forEach((item, index, array) => item + ' ' + index) /* Add an index */ | |
.reduce((total, item, index, array) => { | |
index !== array.length - 1 ? total += item + ' and ' : total += item; // Concat into one string and add 'and', unless its the last element | |
return total; // Return the cumulative total | |
}, '' /* Initial value, can be any primitive e.g. [], boolean etc */); | |
// Outputs: "apple juice and orange juice and lime juice" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment