The most common javascript array function, you should need to know.
- concate(): This function is used to join two or more array without change the existing array:
const arr1 = ['1', '2', '3'];
const arr2 = ['4', '5', '6'];
const res = arr1.concat(arr2);
console.log(res);Output: [ '1', '2', '3', '4', '5', '6' ]
2. filter(): It creates a new array with elements that pass under specific criteria from an array. for example find a number that is greater than 18
let numbers = [10, 31, 26, 18, 11];
let res = numbers.filter(num => num > 18)
console.log(res);Output: [ 31, 26 ]
3. map(): Javascript map() method accepts a callback function and returns a new array. for example convert double of an array element.
var numbers = [10, 31, 26, 18, 11];
var res = numbers.map(num => num * 2)
console.log(res);Output: [ 20, 62, 52, 36, 22 ]
4. reduce(): reduce an array element and return a single value. for example sum of a given array element. reduce method takes a callback function which takes two parameters as argument accumulator and currentValue. accumulator stores the result and currentValue is every element of an array.
var numbers = [10, 31, 26, 18, 11];
var res = numbers.reduce((acc,cur)=>acc+cur);
console.log(res);Output: 96
5. find(): Its return the first matches element of an array that passes under specific criteria. For example, return a number that is greater than 18.
var numbers = [10, 31, 26, 18, 11];
var res = numbers.find(num=>num>18);
console.log(res);Output: 96
Note: filter() return all elements but find() returns only the first match element that satisfies the provided condition.
6. reverse(): Reverse an array. example
let numbers = [10, 31, 26, 18, 11];
let res = numbers.reverse();
console.log(res);Output :[ 11, 18, 26, 31, 10 ]
7. sort(): Short an array with ascending order. example
let numbers = [10, 31, 26, 18, 11];
let res = numbers.sort();
console.log(res);Output :[ 10, 11, 18, 26, 31 ]
8. forEach(): Loop through the array and return each element of an array
let numbers = [10, 31, 26, 18, 11];numbers.forEach(num =>console.log("Num :",num))Output: Num : 10
Num : 31
Num : 26
Num : 18
Num : 11
9.push(): Insert a new element at the end of an array
let numbers = [10, 31, 26, 18, 11];
numbers.push(100);
console.log(numbers);Output: [ 10, 31, 26, 18, 11, 100 ]
10. unshift(): Insert a new element at the beginning of an array.
let numbers = [10, 31, 26, 18, 11];
numbers.unshift(100);
console.log(numbers);Output: [ 100, 10, 31, 26, 18, 11 ]
11. pop(): Delete an element at the end of an array
let numbers = [10, 31, 26, 18, 11];
numbers.pop();
console.log(numbers);Output: [ 10, 31, 26, 18 ]
12. shift(): Remove an element at the beginning of an array.
let numbers = [10, 31, 26, 18, 11];
numbers.shift();
console.log(numbers);Output: [ 31, 26, 18, 11 ]
Happy Coding !! ❤️❤️❤️❤️❤️❤️