Methods
1. forEach() | 2. map() | 3. filter() | 4. reduce() |
5. slice() | 6. splice() | 7. sort() | 8. concat() |
9. fill() | 10. includes() | 11. join() | 12. reverse() |
13. push() | 14. pop() | 15. unshift() | 16. shift() |
17. indexOf() | 18. lastIndexOf() | 19. every() | 20. some() |
21. find() | 22. findIndex() | 23. from() | 24. isArray() |
25. flat() |
1. forEach()
The forEach() method executes a provided function once for each array element.
const numArr = [1,2,3,4,5,6,7,8,9,10];
let sum = 0;
numArr.forEach((elem, index, arr) => {
console.log(`numArr[${index}] - ${elem}`)
sum +=elem;
})
console.log(sum) //55
2. map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
// returns a new array and does not change the original array
const numArr = [1,2,3,4,5,6,7,8,9,10];
const newArr = numArr.map((elem, index, array) => {
return elem*index
});
console.log(numArr); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(newArr); // [ 0, 2, 6, 12, 20, 30, 42, 56, 72, 90 ]
Another Array.map() example:
// finding total price of each item
const productsArr = [
{
name: "Laptop",
price: 1000,
count: 8
},
{
name: "Mouse",
price: 500,
count: 5
},
{
name: "Keyboard",
price: 800,
count: 4
}
];
const newArr = productsArr.map(product => {
return ({
name: product.name,
totalPrice: product.price * product.count
});
});
console.log(newArr);
/*
[ { name: 'Laptop', totalPrice: 8000 },
{ name: 'Mouse', totalPrice: 2500 },
{ name: 'Keyboard', totalPrice: 3200 } ]
*/
Another Array.map() example:
// converting array of strings to numbers
const strArr = ["1","2","3","4","a","5"];
const numArr = strArr.map(Number);
console.log(strArr)
console.log(numArr) // [ 1, 2, 3, 4, NaN, 5 ]
3. filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
// finding even
const numArr = [1,2,3,4,5,6,7,8,9,10];
const evenArray = numArr.filter(elem => {
return elem %2 === 0;
});
console.log(evenArray); // [ 2, 4, 6, 8, 10 ]
Another Array.filter() example:
// finding persons above 18 yrs age
const personsArr = [
{
name: "John",
age: 12
},
{
name: "Mary",
age: 21
},
{
name: "William",
age: 50
}
]
const adultArr = personsArr.filter(person => person.age > 18);
console.log(adultArr)
/*
[
{
name: 'Mary',
age: 21
},
{
name: 'William',
age: 50
}
]
*/
4. reduce()
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
/* the last parameter is the initial value of the accumulator, the accumulator basically stores the persisting value on every iteration */
// find the sum of all elems
const numArr = [1,2,3,4,5,6,7,8,9,10];
const totalVal = numArr.reduce((accumulator, elem, index, arr) => {
return accumulator + elem;
},0);
console.log(totalVal); //55
Another Array.reduce() example:
// find the max value
const numArr = [1,2,3,4,5, 99, 6,7,8,9,10];
const maxVal = numArr.reduce((accumulator, elem, index, arr) => {
return accumulator > elem ? accumulator : elem
}, 0);
console.log(maxVal); // 99
Another Array.reduce() example:
// find total worth of all products
const productsArr = [
{
name: "Laptop",
price: 1000,
count: 8
},
{
name: "Mouse",
price: 500,
count: 5
},
{
name: "Keyboard",
price: 800,
count: 4
}
];
const totalWorth = productsArr.reduce((accumulator, elem, index, arr) => {
return accumulator += elem.price * elem.count;
},0);
console.log(totalWorth); // 13700
5. slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start
to end
(end
not included) where start
and end
represent the index of items in that array. The original array will not be modified.
// does not include the second argument as index into consideration
const numArr = [1,2,3,4,5,6,7,8,9,10];
let slicedArr = numArr.slice(-5,-1);
console.log(slicedArr); // [ 6, 7, 8, 9 ]
slicedArr = numArr.slice(1,5);
console.log(slicedArr); // [ 2, 3, 4, 5 ]
6. splice()
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.
// manipulates the original array and returns the array of removed elements
const numArr = [1,2,3,4,5,6,7,8,9,10];
const removedElems = numArr.splice(5,3);
console.log(removedElems); // [ 6, 7, 8 ]
console.log(numArr); // [ 1, 2, 3, 4, 5, 9, 10 ]
Another example of array.splice():
// remove and insert elements into array
const numArr = [1,2,3,4,5,6,7,8,9,10];
const removedElems = numArr.splice(5,3, "a", "b", "c");
console.log(removedElems); //[ 6, 7, 8 ]
console.log(numArr); // [ 1, 2, 3, 4, 5, 'a', 'b', 'c', 9, 10 ]
Another example of Array.splice():
// insert an array
const numArr = [1,2,3,4,5,6,7,8,9,10];
const removedElems = numArr.splice(5,3, ["a", "b", "c"]);
console.log(removedElems); // [ 6, 7, 8 ]
console.log(numArr); // [ 1, 2, 3, 4, 5, [ "a", "b", "c" ], 9, 10 ]
Another example of Array.splice():
// using the spread operator
const numArr = [1,2,3,4,5,6,7,8,9,10];
const removedElems = numArr.splice(5,3, ...["a", "b", "c"]);
console.log(removedElems); // [ 6, 7, 8 ]
console.log(numArr); // [ 1, 2, 3, 4, 5, 'a', 'b', 'c', 9, 10 ]
7. sort()
The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
/* converts the elements into strings and compares their UTF-16 code values
this manipulates the original array */
const charArr = ["C", "Z", "A", "B", "X", "D", "Y"]
const sortedCharArr = charArr.sort();
console.log(charArr); // [ 'A', 'B', 'C', 'D', 'X', 'Y', 'Z' ]
console.log(sortedCharArr); // [ 'A', 'B', 'C', 'D', 'X', 'Y', 'Z' ]
Another example of Array.sort():
// sorting a number array by writing a custom comparison function
const numArr = [6, 7, 10, 1, 2, 8, 9, 3, 4, 5];
const sortedNumArr = numArr.sort((a, b) => {
/*
1. Negative result will return a
2. Zero result will do nothing
3. Positive result will return b
*/
return (a - b);
});
console.log(numArr);
console.log(sortedNumArr); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Another example of Array.sort():
// sort number array in reverse
const numArr = [6, 7, 10, 1, 2, 8, 9, 3, 4, 5];
const sortedNumArr = numArr.sort((a, b) => b - a);
console.log(numArr);
console.log(sortedNumArr); // [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
8. concat()
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
const numArr1 = [1, 2, 3];
const numArr2 = [4, 5, 6];
const numArr3 = [7, 8, 9, 10];
const newArr1 = numArr1.concat(numArr2, numArr3);
console.log(newArr1); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
const newArr2 = numArr1.concat(77, 88, 99, 100);
console.log(newArr2); // [ 1, 2, 3, 77, 88, 99, 100 ]
const newArr3 = numArr1.concat([11, 22, 33, 44]);
console.log(newArr3); // [ 1, 2, 3, 11, 22, 33, 44 ]
const newArr4 = numArr1.concat(...[11, 22, 33, 44]);
console.log(newArr4); // [ 1, 2, 3, 11, 22, 33, 44 ]
const newArr5 = numArr1.concat("a", "b", "c", numArr2, numArr3);
console.log(newArr5); // [ 1, 2, 3, 'a', 'b', 'c', 4, 5, 6, 7, 8, 9, 10 ]
9. fill()
The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length
). It returns the modified array.
// used to fill in an array with certain elements can also take index as an argument
const numArr = [1,2,3,4,5,6,7,8,9,10];
const newArr1 = numArr.fill(0);
console.log(newArr1); // [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
const newArr2 = numArr.fill("$",1,7);
console.log(newArr2); // [ 0, '$', '$', '$', '$', '$', '$', 0, 0, 0 ]
const newArr3 = numArr.fill("#", -3);
console.log(newArr3); // [ 0, '$', '$', '$', '$', '$', '$', '#', '#', '#' ]
Another example of Array.fill():
// generate number array using fill()
const createNumArr = (value) => {
return Array(value).fill(0).map((elem, index) => {
return index + 1;
});
}
const newArr1 = createNumArr(7)
console.log(newArr1); // [ 1, 2, 3, 4, 5, 6, 7 ]
10. includes()
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
// checks if an element includes in the array
const myArr = ["Tokyo", "Paris", "Italy"];
const res1 = myArr.includes("London");
console.log(res1); //false
const res2 = myArr.includes("Paris");
console.log(res2); //true
11. join()
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
/* joins all the elements from an array separated by
separator of your choice (default is a comma) and forms
a new string */
const myArr = ["Tokyo", "Paris", "Italy"];
const res1 = myArr.join();
console.log(res1); // Tokyo,Paris,Italy
const res2 = myArr.join("|");
console.log(res2); // Tokyo|Paris|Italy
12. reverse()
The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.
/* reverses the array element, since it manipulates the
original array hence we can create a shallow copy using concat anything
or use the spread operator to work on a new array on the fly */
const numArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const revNumArr = [...numArr].reverse();
console.log(numArr); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(revNumArr); // [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
const charArr = [ 'A', 'B', 'C', 'D', 'X', 'Y', 'Z' ];
const revCharArr = [...charArr].reverse();
console.log(charArr); // [ 'A', 'B', 'C', 'D', 'X', 'Y', 'Z' ]
console.log(revCharArr); // [ 'Z', 'Y', 'X', 'D', 'C', 'B', 'A' ]
Another example of reverse():
// reverse a string
const myStr = "Moonlight is horrible !!";
const revMyStr1 = myStr.split(" ").reverse().join(" ");
const revMyStr2 = myStr.split("").reverse().join("");
console.log(revMyStr1); // !! horrible is Moonlight
console.log(revMyStr2); // !! elbirroh si thgilnooM
13. push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
// add elements to the end of the array and returns the new length
const numArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const res = numArr.push(11,12,13);
console.log(numArr); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
console.log(res) // 13
14. pop()
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
// removes the last element of the array and returns the removed element
const numArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const res = numArr.pop();
console.log(numArr); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
console.log(res) // 10
15. unshift()
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
// add elements to the beginning of the array and returns the new length
const numArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const res1 = numArr.unshift(11);
console.log(numArr); // [ 11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(res1); // 11
const res2 = numArr.unshift(12, 13);
// adds from the right
console.log(numArr); // [ 12, 13, 11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(res2); // 13
16. shift()
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
// removes the first element from an array and returns the removed element
const numArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const res = numArr.shift();
console.log(numArr); // [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(res); // 1
17. indexOf()
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
const nameArr = ["Fred", "Dorothy", "Barney", "William"]
const res = nameArr.indexOf("Barney");
console.log(res); // 2
const res2 = nameArr.indexOf("Jayden");
// if an elem is not found it will return -1
res2 > -1 ? console.log(res2) : nameArr.push("Jayden")
console.log(nameArr.indexOf("Jayden")); // 4
18. lastIndexOf()
The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.
// returns the index of the last matching element
const nameArr = ["Fred", "Dorothy", "Barney", "William", "Dorothy"]
const res = nameArr.lastIndexOf("Dorothy");
console.log(res); // 4
19. every()
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
/* returns true/false based on an operation carried on all the elems of an object
if any one elem does not match the condition, it will return false */
const numArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const res1 = numArr.every((elem, index, arr) => {
return elem % 5 === 0;
});
console.log(res1); // false
const res2 = numArr.every((elem, index, arr) => {
return elem > 0
});
console.log(res2); // true
Another example of Array.every():
// checking a 2D array
const twoDArr = [
[1,2,3],
[4,5,6],
[7,8,9]
];
const res = twoDArr.every((item, index, arr) => {
return Array.isArray(item);
});
console.log(res) // true
20. some()
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
/* returns true/false based on an operation carried on all the elems of an object
if any one element matches the condition it will reurn true */
const numArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const res1 = numArr.some((elem, index, arr) => {
return elem % 5 === 0;
});
console.log(res1); // true
const res2 = numArr.some((elem, index, arr) => {
return elem > 10
});
console.log(res2); // false
21. find()
The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined
is returned.
// finds an element from an array and returns the element itself
const persons = [
{
name: "Fred",
age: 25
},
{
name: "Dorothy",
age: 50
},
{
name: "William",
age: 47
},
{
name: "Jayden",
age: 19
}
];
const res = persons.find((person, index, arr) => {
return person.name === "William";
});
console.log(res); // { name: 'William', age: 47 }
console.log(res.age); // 47
22. findIndex()
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
// finds an element from an array and returns the index of it
const persons = [
{
name: "Fred",
age: 25
},
{
name: "Dorothy",
age: 50
},
{
name: "William",
age: 47
},
{
name: "Jayden",
age: 19
}
];
const res = persons.findIndex((person, index, arr) => {
return person.name === "William";
});
console.log(res); // 2
console.log(persons[res].age); // 47
23. from()
The Array.from()* static method creates a new, shallow-copied Array instance from an array-like or iterable object.
// creates an array from a string
const numArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const myStr = "123456789";
const res = Array.from(myStr, (elem, index, array) => {
return Number(elem)
});
const res2 = Array.from(myStr, Number);
console.log(res); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
console.log(res2); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Another exampleof Array.from():
// remove dupes from an array
const faultyArr = [1, 2, 3, 1, 2, 3, 4, 5];
const uniqueSet = new Set(faultyArr);
console.log(uniqueSet); // Set { 1, 2, 3, 4, 5 }
const uniqueArr = Array.from(uniqueSet);
console.log(uniqueArr); // [ 1, 2, 3, 4, 5 ]
24. isArray()
The Array.isArray() method determines whether the passed value is an Array
.
// check if the arguement passed is an array type
const numArr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const myString = "JavaScript";
let res = Array.isArray(numArr);
console.log(res); // true
res = Array.isArray(myString);
console.log(res); // false
25. flat()
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
/* creates a new new array with all the sub arrays elems
by default the depth is 1 but you can mention the depth or just Infinity */
const numArr = [ 1, 2, [3, 4, [5, [6, 7], 8,], 9, 10 ]];
let res = numArr.flat(3); // can also use Infinity
console.log(res); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Top comments (0)