You are on page 1of 20

Array method

concat()
 The concat() method concatenates (joins) two or more arrays.
 The concat() method returns a new array, containing the joined arrays.
 The concat() method does not change the existing arrays.

console.log('concat methode')

let a = ["some", "favourite", " food", "are"]

let b = ["apple", "mango"];

let c = ["and", "banana"];

let d = a.concat(b, c);

console.log(d)

entries()
The entries() method returns an Array Iterator object with key/value
pairs

entries() will visit empty slots as if they are undefined

let a = ["some", "favourite", " food", "are"]

let d = a.entries();

for(let x of d)

console.log(x)

o/p:- entries methode

[ 0, 'some' ]

[ 1, 'favourite' ]

[ 2, ' food' ]
[ 3, 'are' ]

every()
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
Due)

The every() method executes a function for each array element.

The every() method returns true if the function returns true for all elements.

The every() method returns false if the function returns false for one element.

The every() method does not execute the function for empty elements.

fill()
The fill() method fills specified elements in an array with a value.

The fill() method overwrites the original array.

Start and end position can be specified. If not, all elements will be filled.

1st element of array cant change through fill() method

const fruits = ["Banana", "Orange", "Apple", "Mango"];

let a=fruits.fill("Kiwi",2,4);

console.log(a);

o/p:-

[ 'Banana', 'Orange', 'Kiwi', 'Kiwi' ]

push()
The push() method adds new items to the end of an array.

The push() method changes the length of the array.

The push() method returns the new length


let name = ['Kaustav', 'Akash', 'Riju', 'Swaraj', 'Rupam'];
console.log('at first show the main array and understand the array index possition');
console.log(name);
console.log('now we will push pijus in last of the index (6 index)');
name.push('pijus');
console.log('after pushing elemet now we will again show array');
console.log(name);
o/p:-
at first show the main array and understand the array index possition
[ 'Kaustav', 'Akash', 'Riju', 'Swaraj', 'Rupam' ]
now we will push pijus in last of the index (6 index)
after pushing elemet now we will again show array
[ 'Kaustav', 'Akash', 'Riju', 'Swaraj', 'Rupam', 'pijus' ]

...............ANOTHER WAY..............
let name = ['Kaustav', 'Akash', 'Riju', 'Swaraj', 'Rupam'];
console.log('at first show the main array and understand the array index possition');
console.log(name);
console.log('now we will push pijus in last of the index (6 index)');
name.push('pijus');
console.log('after pushing elemet now we will again show array');
for(let i in name)
{
console.log(name[i])
}
O/P:-
at first show the main array and understand the array index possition
[ 'Kaustav', 'Akash', 'Riju', 'Swaraj', 'Rupam' ]
now we will push pijus in last of the index (6 index)
after pushing elemet now we will again show array
Kaustav
Akash
Riju
Swaraj
Rupam
Pijus
pop()
The pop() method removes (pops) the last element of an array.

The pop() method changes the original array.

The pop() method returns the removed element

Ex:-
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]

o/p:-
> "tomato"
> Array ["broccoli", "cauliflower", "cabbage", "kale"]
> Array ["broccoli", "cauliflower", "cabbage"]

let a=[10,11,12,13,14,15];

console.log('............................pop function...........');
console.log('now we will delete 100 of last index');
a.pop(100);
console.log('after delete last element using pop function the array will be:--');
console.log(a);

o/p:-
10,11,12,13,14

shift()
The shift() method removes the first item of an array.

The shift() method changes the original array.

The shift() method returns the shifted element.


Syntax
array.shift()
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(“at first print the original array”);
console.log(fruits);
fruits.shift();
console.log(“after using shift methor the array will be”);
console.log(fruits);

o/p:-
"Orange", "Apple", "Mango"

unshift()
The unshift() method adds new elements to the beginning of an array.

The unshift() method overwrites the original array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(“at first print the original array”);
console.log(fruits);
fruits.unshift("Lemon","Pineapple");
console.log(“after using unnshift methor the array will be”);
console.log(fruits);

o/p:- "Lemon","Pineapple","Banana", "Orange", "Apple", "Mango"

splice()
The splice() method adds and/or removes array elements.

The splice() method overwrites the original array.

Syntax
array.splice(index, howmany, item1, ....., itemX)
Parameter Description

index Required.
The position to add/remove items.
Negative value defines the position from the end of the array.

howmany Optional.
Number of items to be removed.

item1, ..., item Optional.


X New elements(s) to be added.

Example1:-
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// At position 2, add 2 elements:
fruits.splice(2, 0, "Lemon", "Kiwi");
console.log(fruits);
o/p:- ["Banana", "Orange" ,"Lemon", "Kiwi", "Apple", "Mango"]

the first parameter (2) defines the position where new elements should be added (spliced in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

Example2:-
const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
// At position 2, remove 2 items:
fruits.splice(2, 2);
console.log(fruits);
o/p:- "Banana" ,"Banana" ,"Kiwi"

Using splice() to Remove Elements

With clever parameter setting, you can use splice() to remove elements without leaving
"holes" in the array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);

The first parameter (0) defines the position where new elements should be added (spliced in).

The second parameter (1) defines how many elements should be removed.

The rest of the parameters are omitted. No new elements will be added.

slice()
The slice() method slices out a piece of an array into a new array.

The slice( ) method copies a given part of an array and returns that copied part as a new array.
It doesn't change the original array. The splice( ) method changes an array, by adding or
removing elements from it.

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];


const citrus = fruits.slice(1);

console.log(“citrus”); // Orange,Lemon,Apple,Mango

const fruits1 = ["Banana", "Orange", "Lemon", "Apple", "Mango"];


const citrus1 = fruits.slice(2);

console.log(“citrus”); // Lemon,Apple,Mango

 he slice() method can take two arguments like slice(1, 3)

const fruits2 = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

const citrus2 = fruits.slice(1,3);

console.log(“citrus”); // Orange,Lemon

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

filter()
The filter() method returns a new array with all elements that pass the test defined by the given
function.

filter() does not change the original array.

Syntax:-
array.forEach(function(currentValue, index, arr))

Here,

 function(currentValue, index, arr) - a function to be run for each element of an array


 currentValue - It is required parameter and it holds the value of current element.
 index (optional) - It is optional parameter and it holds the index of current element.arr
(optional) - It is optional parameter and it holds the array.

Using arrow function


const a =[1,2,3,4,10,22,77,88]

let b= a.filter( (a)=>


{
return a>3
});
console.log(b)
normal filter use without arrow function:-
const a =[1,2,3,4,10,22,77,88]
function fun2(a) {
if(a>10)
return true;
else
return false;
}

let c= a.filter(fun2)
console.log(c)

Filtering out values from Array


const prices = [1800, 2000, null, 3000, 5000, "Thousand", 500, 8000]

function checkPrice(element) {
return element > 2000 && !Number.isNaN(element);
}

let filteredPrices = prices.filter(checkPrice);

console.log(filteredPrices); // [ 3000, 5000, 8000 ]

// using arrow function


let newPrices = prices.filter((price) => (price > 2000 && !
Number.isNaN(price)));

console.log(newPrices); // [ 3000, 5000, 8000 ]

Output

[ 3000, 5000, 8000 ]


[ 3000, 5000, 8000 ]

forEach():- (it is a loop)


the for Each calls a provided function once for each element in array, The forEach() method can also
be used on Maps and Sets. For each loop does not create new array where map() create a new array,

JavaScript forEach

The syntax of the forEach() method is:

array.forEach(function(currentValue, index, arr))

Here,

 function(currentValue, index, arr) - a function to be run for each element of an array


 currentValue - It is required parameter and it holds the value of current element.
 index (optional) - It is optional parameter and it holds the index of current element.arr
(optional) - It is optional parameter and it holds the array.

forEach with Arrays

let arr = ['rupam', 27, 'swaraj', 16];

arr.forEach(myfunction);

function myfunction(value , index, arr) {

console.log(value,index,arr);

o/p:-

rupam 0 [ 'rupam', 27, 'swaraj', 16 ]

27 1 [ 'rupam', 27, 'swaraj', 16 ]

swaraj 2 [ 'rupam', 27, 'swaraj', 16 ]

16 3 [ 'rupam', 27, 'swaraj', 16 ]

Updating the Array Elements

let students = ['John', 'Sara', 'Jack'];

// using forEach
students.forEach(myFunction);

function myFunction(item, index, arr) {


arr[index] = 'hello ' + item

}
console.log(students);

Output

["Hello John", "Hello Sara", "Hello Jack"]

forEach with Arrow Function


// with arrow function and callback

const students = ['John', 'Sara', 'Jack'];


students.forEach(element => {
console.log(element);
});

Output

John
Sara
Jack

forEach...of with Sets

You can iterate through the Set elements using the forEach() method. For example,

// define Set
const set = new Set([1, 2, 3]);

// looping through Set


set.forEach(myFunction);

function myFunction(item) {
console.log(item);
}
Run Code

Output

1
2
3

forEach with Maps

You can iterate through the Map elements using the forEach() method. For example,

let map = new Map();

// inserting elements
map.set('name', 'Jack');
map.set('age', '27');

// looping through Map


map.forEach (myFunction);

function myFunction(value, key) {

console.log(key + '- ' + value);


}
Run Code

Output

name- Jack
age- 27

let arr=[22,33,44,55,66,6,77];
arr.forEach(function1)
function function1(value,index,arr)
{
console.log("array is"+ arr +"value is:-" +value + "index umber is:-" +index);
}

map() :-
It creates an array by calling a specific function on each element present in the parent array. The
map() method creates a new array by performing some operation on each array element.

map() calls a function once for each element in an array.


map() does not change the original array.
map() does not execute the function for empty elements

map() Parameters

The map() method takes in:

 callback - The function called for every array element. Its return values are added to the new
array.

.Syntax:
array.map(function(currentValue, index, arr), thisValue)

Parameters: This method accepts two parameters as mentioned above and described below:

 function(currentValue, index, arr): It is required parameter and it runs on each


element of array. It contains three parameters which are listed below:
o currentValue: It is required parameter and it holds the value of current
element.
o index: It is optional parameter and it holds the index of current element.
o arr: It is optional parameter and it holds the array.
 thisValue: It is optional parameter and used to hold the value of passed to the
function.

let numbers = [2, 4, 6, 8, 10];

// function to return the square of a number


function square(number) {
return number * number;
}

// apply square() function to each item of the numbers list


let square_numbers = numbers.map(square);

console.log(square_numbers);

// Output: [ 4, 16, 36, 64, 100 ]

const numbers = [1, 4, 9];


const roots = numbers.map((num) => Math.sqrt(num));

// roots is now [1, 2, 3]


// numbers is still [1, 4, 9]

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>Compute a new array with the full name of each person in the old array:</p>

<p id="demo"></p>

<script>
const persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];

document.getElementById("demo").innerHTML = persons.map(getFullName);

function getFullName(item) {
return [item.firstname,item.lastname].join(" ");
}
</script>

</body>
</html> // output is Malcom Reynolds,Kaylee Frye,Jayne Cobb

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>

<p>Compute a new array with the full name of each person in the old array:</p>

<p id="demo"></p>

<script>

let details =[
{ name: 'rupam' ,age:17},
{ name: 'rupam1' ,age:179},
{ name: 'rupam3' ,age:197}
];

document.getElementById("demo").innerHTML=details.map(det);
function det(item){
return [item.name,item.age].join(" age is ");
}

</script>

</body>
</html> // o/p:= rupam age is 17,rupam1 age is 179,rupam3 age is 197

reduce()
The reduce() method executes a reducer function on each element of the array and returns a
single output value

The reduce() method does not execute the function for empty array elements.

The reduce() method does not change the original array.

Syntax
// Arrow function

reduce((previousValue/accumulator, currentValue, currentIndex, array) => { /* … */ }


// Callback function
reduce(callbackFn, initialValue)

Sum of All Values of Array


const numbers = [1, 2, 3, 4, 5, 6];

function sum_reducer(accumulator, currentValue) {


return accumulator + currentValue;
}
let sum = numbers.reduce(sum_reducer);

console.log(sum); // 21

// using arrow function


let summation = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue
);

console.log(summation); // 21
Run Code

Output

21
21

Subtracting Numbers in Array


const numbers = [1800, 50, 300, 20, 100];

// subtract all numbers from first number


// since 1st element is called as accumulator rather than currentValue
// 1800 - 50 - 300 - 20 - 100
let difference = numbers.reduce(
(accumulator, currentValue) => accumulator - currentValue
);

console.log(difference); // 1330

find()
The find() method returns the value of the first element that passes a test.

The find() method executes a function for each array element.

The find() method returns the value of the first array element that satisfies the provided test
function.

Returns undefined if none of the elements satisfy the function.

The find() method does not execute the function for empty elements.

The find() method does not change the original array.

Syntax
array.find(function(currentValue, index, arr),thisValue)
Parameters
1. Required.
function() A function to run for
each array element.
2. Required.
currentValue The value of the current
element.
3. Optional.
index The index of the current
element.
4. Optional.
arr The array of the current
element.
5. Optional. Default
undefined.
thisValue A value passed to the
function as its this
value.

// Arrow function
find((element, index, array) => { /* … */ } )
// Callback function
find(callbackFn, thisArg)
// Inline callback function
find(function(element, index, array) { /* … */ }, thisArg)

EXAMPLE:-
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12
EXAMPLE:-

const student=[
{
name: 'rupam',class:6,sec:'a'
},
{
name: 'rupam2',class:7,sec:'b'
},
{
name: 'rupam22',class:88,sec:'f'
},
];

let classes = student.find((exam) => {


return exam.class>1
})
console.log(classes) // OUTPUT { name: 'rupam', class: 6, sec: 'a' }
console.log(classes.name, classes.sec) // OUTPUT rupam a

 The findIndex() method returns the index (position) of the first element that passes a
test.
const array1 = [5, 12, 8, 130, 44];

const found = array1.findIndex(element => element > 10);

console.log(found);
// expected output: 1

every()
The every() method executes a function for each array element.

The every() method returns true if the function returns true for all elements.

The every() method returns false if the function returns false for one element.

The every() method does not execute the function for empty elements.

The every() method does not change the original array

// Arrow function
every((element, index, array) => { /* … */

// Callback function
every(callbackFn, thisArg)

// Inline callback function


every(function(element, index, array){ /* … */ })
Check Value of Array Element
function checkAdult(age) {
return age >= 18;
}

const ageArray = [34, 23, 20, 26, 12];


let check = ageArray.every(checkAdult); // false

if (!check) {
console.log("All members must be at least 18 years of age.")
}

// using arrow function


let check1 = ageArray.every(age => age >= 18); // false
console.log(check1);
Run Code

Output

All members must be at least 18 years of age.


false

includes()

The includes() method returns true if an array contains a specified value.

The includes() method returns false if the value is not found.

const array1 = [5, 12, 8, 130, 44];


const ac = array1.includes(5)
console.log(ac); // output true

join()
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = fruits.join(" and ");
console.log(text); // output Banana and Orange and Apple and Mango

The join() method returns an array as a string.

The join() method does not change the original array.


toString()
toString() converts an array to a string of (comma separated) array values.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Result:

Banana,Orange,Apple,Mango

join()
The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");

Result:

Banana * Orange * Apple * Mango

Sorting an Array
The sort() method sorts an array alphabetically:

Reversing an Array

The reverse() method reverses the elements in an array.

You can use it to sort an array in descending order:


String includes():-
 The includes() method returns true if a string contains a specified string.
 Otherwise it returns false.
 The includes() method is case sensitive.

Differences between forEach() and map() methods:

 The forEach() method does not create a new array based on the
given array. Where The map() method creates an entirely new array.

 The forEach() method returns “undefined“. Where The map() method


returns the newly created array according to the provided callback
function.

You might also like