# Must know magical array methods to get start over React, Angular, Vue and other Javascript Frameworks/Libraries.
Hi, This is Jhani Mohammad. An enthusiast and aspiring React front-end engineer. Here, I'm going to share the most important array of methods that are often used in Javascript programming and its associated Frameworks/Libraries. It's essential to know to beginners on the journey with React or any other Javascript Frameworks/Libraries. Each topic covers with few examples and problem sets. I will make sure this post is clear and you get good knowledge about these topics.
Here are the following topics, I'll be covering in this section.
forEach
Map
Filter
Some
Every
Reduce
Before I start, make sure you understand each topic and have some practice with the given examples. I'll be dividing each topic into its own block. So, it will get easier to understand and get it. I bet you'll be having a good time with these topics. So, Let's get started.
Let's begin with our first array family, ie, forEach!
.forEach
Imagine working on larger projects and you still work with basic old for loop
syntax. Yes, you can absolutely use it but your code might look bulky and old-fashioned way. What if we can achieve the same goal by using fewer lines of code, make sense right?
.forEach()
is easier. Even though it’s the same number of lines, there’s less setup.
forEach()
is a generic tool. when you can’t use other array methods to accomplish your goal, then .forEach is your perfect partner.
okay, enough talking. Let's dive into it!
The .forEach
method is one of the several ways to loop through arrays. We can make a new array and use forEach to push values into the new array.
Note to yourself .forEach
always returns undefined and very commonly we transform one array into another array with different values.
Anotomy
It iterates through an array.
Runs a callback function for each value in the array.
returns 'undefined'.
-> We can call the parameters to the callback. -> We do not always need all three parameters. Use which you need, Just remember the order is important.
An example
let arr = [1, 2, 3];
arr.forEach((val, idx, arr) => {
console.log(val);
});
/* OUTPUT
1
2
3
undefined
*/
Functions that do not have a return keyword will always output undefined.
Using .forEach
in a function.
const halfValues = (arr) => {
let newArr = [];
arr.forEach((val) => {
newArr.push(val / 2);
});
return newArr;
};
halfValues([2, 3, 4]);
/* OUTPUT
(3) [1, 1.5, 2]
*/
Let's practice some problem sets.
1. Let's write a function called onlyEvenValues which accepts an array and returns a new array with only the even values in the array passed to the function.
const onlyEvenValues = (arr) => { let newArr = \[\]; arr.forEach((val) => { if (val % 2 == 0) { newArr.push(val); } }); return newArr; };
onlyEvenValues(\[1, 2, 3, 4, 5\]);
/\* OUTPUT (2) \[2, 4\] \*/
```plaintext
###### 2. Let's write a function called *showFirstAndLast* which accepts an array of strings and returns a new array with only the first and last character of each string.
const showFirstAndLast = (arr) => { let newArr = []; arr.forEach((val) => { newArr.push(val[0] + val[val.length - 1]); }); return newArr; };
showFirstAndLast(['Liam', 'Emma'])
/* OUTPUT (2) ['Lm', 'Ea'] */
###### 3. Let's write a function called *addKeyAndValue* which accepts an array of objects, a key, and a value. which returns the array passed to the function with the new key and value-added for each object.
const addKeyAndValue = (arr, key, value) => { arr.forEach((val) => { val[key] = value; }); return arr; };
addKeyAndValue( [{ name: "Liam" }, { name: "Emma" }, { name: "Oliver" }], "title", "instructor" );
/* OUTPUT 0: {name: 'Liam', title: 'instructor'} 1: {name: 'Emma', title: 'instructor'} 2: {name: 'Oliver', title: 'instructor'} */
###### 4. Let's write a function called *vowelCount* which accepts a string and returns an object with keys as the vowel and the values as the number of times the vowel appears in the string.
const vowelCount = (str) => { let splitStr = str.split(""); let obj = {}; var vowels = "aeiou"; splitStr.forEach((letter) => { if (vowels.indexOf(letter.toLowerCase()) !== -1) { if (letter in obj) { obj[letter]++; } else { obj[letter] = 1; } } }); return obj; };
vowelCount("Charlotte");
/* OUTPUT {a: 1, o: 1, e: 1} */
> Note: .forEach can be used to override values in an array or change something internally.
<hr/>
## `.map`
Yeah, here is my favorite array method `.map`. Very much used and so beautiful it is.
As we already discussed, `.forEach` always returns undefined, and very commonly we'll want to transform one array into another array with different values.
we could make a new array and use `.forEach` to push values into a new array but there's an easier way to do that by using `.map`.
##### Anotomy
![map.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650295726583/DMw6sySL7.png)
- `.map` creates a new array
- Iterates through an array.
- Runs a callback function for each value in the array.
- Adds the result of that callback function to the new array.
- Returns the new array.
###### An example
let arr1 = [1, 2, 3]; arr1.map((val, idx, arr) => { return val * 2; });
/* OUTPUT (3) [1, 2, 3] */
###### Try another example
const tripleValues = (arr) => { return arr.map((val) => { return val * 3; }); }; tripleValues([3, 4, 1, 2]); /* OUTPUT (4) [9, 12, 3, 6] */
###### Let's practice some more problem sets.
###### Let's write a function called *valTimesIndex* which accepts an array and returns a new array with each value multiplied by the index it is currently at in the array.
const valTimesIndex = (arr) => { return arr.map((val, idx) => { return val * idx; }); };
valTimesIndex([1, 2, 3]); /* OUTPUT (3) [0, 2, 6] */
###### Let's write a function called *extractKey* which accepts an array of objects and some keys and returns a new array with the value of that key in each object.
const extractKey = (arr, key) => { return arr.map((val) => { return val[key]; }); };
extractKey([{ name: "Noah" }, { name: "William" }, { name: "Henry" }], "name"); /* OUTPUT (3) ['Noah', 'William', 'Henry'] */
###### Let's write a function called *extractFullName* which accepts an array of objects and returns a new array with the value of the key with a name of 'first' and the value of a key with the name of 'last' in each object and concatenate together with space.
const extractFullName = (arr) => { return arr.map((val) => { return val.first + " " + val.last; }); };
extractFullName([ { first: "Noah", last: "a" }, { first: "William", last: "b" }, { first: "Henry", last: "c" }, ]); /* OUTPUT (3) ['Noah a', 'William b', 'Henry c'] */
> When you would like a new array to be rewritten with the same length, then .map always be the best choice.
<hr/>
## `.filter`
`.filter` is a function that is invoked on arrays and just like `.map` and `.forEach` it accepts a callback function.
It is different than the one we used in `.forEach` and `.map` because the result of the callback function will always be evaluated in boolean.
##### Anotomy
![filter.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650296146198/qvSvpmZgF.png)
- `.filter` creates a new array
- Iterates through an array.
- Runs a callback function for each value in the array.
- If the callback function returns true, that value will be added to the new array.
- If the callback function returns false, that value will be ignored from the new array.
###### An example
let arr = [1, 2, 3];
arr.filter((value, index, array) => { //no need of if statement // Just return an expression // this evaluates to true or false return value < 2; });
/* OUTPUT [1] */
###### Try another example
let instructors = [ { name: "William" }, { name: "Charlotte" }, { name: "Mia" }, { name: "Ava" }, ];
instructors.filter((val, idx, arr) => { return val.name.length > 3; }); /* OUTPUT [{name: 'William'}{name: 'Charlotte'}] */
###### Let's practice some more problem sets.
###### Let's write a function called *filterByValue* which accepts an array of objects with a key and returns a new array with all the objects that contain a respected key.
const filterByValue = (arr, key) => { return arr.filter((val) => { return val[key] != undefined; }); };
filterByValue( [ { first: "William", last: "Son", isDogOwner: true }, { first: "Charlotte", last: "Henry" }, { first: "Benjamin", last: "Isabella", isDogOwner: true }, { first: "James", last: "Amelia" }, ], "isDogOwner" );
/* OUTPUT 0: {first: 'William', last: 'Son', isDogOwner: true} 1: {first: 'Benjamin', last: 'Isabella', isDogOwner: true} */
###### 2. Let's write a function called *find* which accepts an array and a value and returns the first element in the array that has the same value as the second parameter or undefined if the value is not found in the array.
const find = (arr, searchValue) => { return arr.filter((val) => { return val === searchValue; })[0]; };
find([1, 2, 3, 4, 5], 3); /* OUTPUT 3 */
find([1, 2, 3, 4, 5], 10); /* OUTPUT undefined */
###### 3. Let's write a function called find *findInObj* which accepts an array of objects, a key, and some value to search for and returns the first found value in the object.
const findInObj = (arr, key, searchValue) => { return arr.filter((val) => { return val[key] === searchValue; }); };
findInObj( [ { first: "William", last: "Son", isDogOwner: true }, { first: "Charlotte", last: "Henry" }, { first: "Benjamin", last: "Isabella", isDogOwner: true }, { first: "James", last: "Amelia" }, ], "isDogOwner", true ); /* OUTPUT 0: {first: 'William', last: 'Son', isDogOwner: true} 1: {first: 'Benjamin', last: 'Isabella', isDogOwner: true} */
###### 4. Let's write a function called *removeVowels* which accepts a string and returns a new string with all of the vowels removed. Every character in the new string should be lowercased.
const removeVowels = (str) => { let vowels = "aeiou"; return str .toLowerCase() .split("") .filter((val) => { return vowels.indexOf(val) === -1; }) .join(""); };
removeVowels("William"); /* OUTPUT 'wllm' */
###### 5. Let's write a function called *doubleOddNumbers* which accepts an array and returns a new array with all of the odd numbers doubled.
const doubleOddNumbers = (arr) => { return arr .filter((val) => { return val % 2 !== 0; }) .map((val) => { return val * 2; }); };
doubleOddNumbers([1, 2, 3, 4, 5]); /* OUTPUT (3) [2, 6, 10] */
<hr/>
## `.some`
`.some` is a function that is invoked on arrays and iterates through each value in the array.
##### Anotomy
![some.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650296528051/og1rZCcpL.png)
- `.some` Iterates through an array.
- Runs a callback on each value in the array.
- If the callback returns true for at least one single value, returns true.
- otherwise, returns false.
###### An example
var arr4 = [1, 2, 3]; arr.some((val, idx, arr) => { return val > 2; }); /* OUTPUT true */
###### Try another example
const hasComma = (str) => { return str.split("").some((val) => { return val === ","; }); };
hasComma("This is kind"); //false hasComma("This, is kind"); //true
###### Let's practice some more problem sets.
###### 1. Let's write a function called *hasOddNumbers* which accepts an array and returns true if the array contains at least one odd number. else, return false.
const hasOddNumbers = (arr) => { return arr.some((val) => { return val % 2 === 0; }); };
hasOddNumbers([1, 2, 3, 4, 5]); /* OUTPUT true */
###### 2. Let's write a function called *hasZero* which accepts a number and returns true if that number contains at least one zero. else, return false.
const hasZero = (num) => { return num .toString() .split("") .some((val) => { return val === "0"; }); };
hasZero(1000); //true hasZero(1111); //false
<hr/>
## `.every`
`.every `is a function that is invoked on arrays and iterates through each value in the array.
##### Anotomy
![every.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650296743912/kB5cpbNFQA.png)
- .every iterates through an array.
- Runs a callback on each value in the array.
- If the callback returns false for at least a single value, the entire array returns false.
- otherwise, returns true.
###### An example
let arr5 = [-1, -2, -3];
arr5.every((val, idx, arr) => { return val < 0; });
/* OUTPUT true */
###### Try another example
const allLower = (str) => { return str.split("").every((val) => { return val === val.toLowerCase(); }); }; allLower("This is jh"); //false allLower("this is jh"); //true
###### Let's practice some more problem sets.
###### 1. Let's write a function called *hasOnlyOddNumbers* which accepts an array and returns true if all numbers in the array are odd. else, return false.
const hasOnlyOddNumbers = (arr) => { return arr.every((val) => { return val % 2 !== 0; }); };
hasOnlyOddNumbers([1, 3, 5, 7]); //true hasOnlyOddNumbers([1, 3, 5, 10]); //false
###### 2. Let's write a function called *hasNoDuplicates* which accepts an array and returns true if there are no duplicates in the entire array. else, return false.
const hasNoDuplicates = (arr) => { return arr.every((val) => { return arr.indexOf(val) == arr.lastIndexOf(val); }); };
hasNoDuplicates([1, 2, 3, 1]); //false hasNoDuplicates([1, 2, 3, 4]); //true
###### 3. Create a function called *hasCertianKey* which accepts an array of objects and a key. Returns true if every object in the array contains that key, else returns false.
const hasCertianKey = (arr, key) => { return arr.every((val) => { return key in val; }); };
let arr7 = [ { first: "William", last: "Son", isDogOwner: true }, { first: "Charlotte", last: "Henry" }, { first: "Benjamin", last: "Isabella", isDogOwner: true }, { first: "James", last: "Amelia" }, ];
hasCertianKey(arr7, "first"); // true hasCertianKey(arr7, "isDogOwner"); // false
<hr/>
## `.reduce`
##### Anotomy
![accumulator.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650297126837/EKBEs-v7If.png)
- .reduce accepts a callback function and an optional second parameter.
- Iterates through an array.
- Runs a callback on each value in the array.
- The first parameter to the callback is either the first value in the array or the optional second parameter.
- The first parameter to the callback is after called accumulated.
- The returned value from the callback becomes the new value of the accumulator.
###### An example
let arr = [1, 2, 3, 4, 5]; arr.reduce((acc, nextValue) => { return acc + nextValue; }); /* OUTPUT 15 */
![acc1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650298417630/L-t6fjLhU.png)
###### Try another example
let arr = [1, 2, 3, 4, 5]; arr.reduce((acc, nextValue) => { return acc + nextValue; }, 10);
/* OUTPUT 25 */
![acc2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650298429073/MGvkO0-FG.png)
###### lets have another example
let arr = [5, 2, 3, 1, 5]; arr.reduce((acc, nextValue) => { if (nextValue in acc) acc[nextValue]++; else acc[nextValue] = 1; return acc; }, {});
/* OUTPUT {1: 1, 2: 1, 3: 1, 5: 2} */
![acc3.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650298439306/vdLrZjDg9.png)
###### Let's practice some more problem sets.
###### 1. Let's write a function called *extractValue* which accepts an array of objects and a key. It returns a new array with the value of each object at the key.
const extractValue = (arr, key) => { return arr.reduce((acc, next) => { acc.push(next[key]); return acc; }, []); };
let exArr = [ { first: "William", last: "Son", isDogOwner: true }, { first: "Charlotte", last: "Henry" }, { first: "Benjamin", last: "Isabella", isDogOwner: true }, { first: "James", last: "Amelia" }, ];
extractValue(exArr, "first");
/* OUTPUT (4) ['William', 'Charlotte', 'Benjamin', 'James'] */
###### 2. Let's write a function called *vowelCount* which accepts a string and returns an object with the key as the vowel and the values as the number of times the vowel appeared in the string.
const vowelCountRe = (str) => { let vowels = "aeiou"; return str.split("").reduce((acc, next) => { if (vowels.indexOf(next.toLowerCase()) !== -1) { if (next in acc) acc[next]++; else acc[next] = 1; } return acc; }, {}); };
vowelCountRe("James JAck");
/* OUTPUT {a: 1, e: 1, A: 1} */
<hr />
Are we done already? Well, yeah!
To the extreme beginners, it looks mindblowing to you. Do not discourage there, just practice it, again and again, then you will start loving it. you can find more sources on [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).