DEV Community

Pranish Shrestha
Pranish Shrestha

Posted on

Arrays in Javascript

Arrays in JavaScript is an object which stores a collection of multiple items in a single variable.

Here are some important JavaScript arrays :

[9,10,23,66].at(-2) //23 

['a','b','c'].concat('h') //['a','b','c','h']

[1, 30, 39, 29, 10, 13].every((x)=> x < 40) //true 

[1,2,3].fill(5,1,2) //[1,5,5]

[2,4,5,6,8].filter((x) => x % 2 === 0) //[2,4,6,8]

[2,4,5,6,8].find((x) => x%2 === 0) //[2]

[2,4,5,6].findIndex((x) => x%2 !==0) //2

[1,2,3].forEach(x => console.log(x)) 
//1
//2
//3

[1,2,3].includes(2) //true

['a','b','c'].join() //"a,b,c"

['a','b','c'].indexOf('a') //0
or ['a','b','c'].indexOf('e') //-1

['a','b','c'].length //3

[1,3,5,7].map((x)=> x*2) //[2,6,10,14]

[1,2,3].push(4) // [1,2,3,4]

[1,2,3].pop() //[1,2]

[1,2,3,4]reduce((prev,cur)=>(prev + cur)) //10

[1,2,3,4].reverse() //[4,3,2,1]

[1,2,3].shift() //1

[2,3,5,6].some((x) => x > 6) //false

[1,10000,5,2,2222,5555,7777,6666].sort() //[1,10000,2,2222,5,5555,6666,7777]

['a','b','c'].slice(1) //['b','c']

['a','b','d','e'].splice(2,0,'c') //['a','b','c','d','e']

destructuring
[a,b] = [10,20] //a= 10 , b=20

...(spread op)
[a,b,...rest] = [10,20,30,40,50]
console.log(rest); //[30,40,50]
console.log(a); [10];


Enter fullscreen mode Exit fullscreen mode

Top comments (0)