Arrays in JavaScript

Important points to note about arrays are given below
  • Arrays are of reference types. (Non Primitives)
  • Arrays can store numbers, strings, objects etc
  • Multi dimensional arrays are supported in JavaScript
  • Each array object supports the methods as defined in Array.prototype
  • Arrays are passed by reference

Array definition Examples


//Array methods
let a = [2,3,'India']
console.log(a.toString()) // output - 2,3,India

//check if element exists
console.log(a.includes(2)) // output - true

//add element from the end
a.push(4)
console.log(a.toString()) // output - 2,3,India,4 

a.push([4,5,6])
console.log(a.toString()) // output - 2,3,India,4,4,5,6

//remove element from the end
console.log(a.pop()) // output - [4,5,6]

console.log(a.toString()) // output - 2,3,India,4

a.shift();
console.log(a.toString()) // output - 3,India,4

a.unshift('65');
console.log(a.toString()) // output - 65,3,India,4

console.log(typeof a[1]) //number

a.splice(2,1)
console.log(a.toString()) // output - 65,3,4


let k = a.slice(0,1)
console.log(a.toString()) // output - 65,3,4

console.log(k.toString()) // output - 65

var emp = [
    { id: 20, name: 'USA' },
    { id: 24, name: 'UK' },
    { id: 56, name: 'Australia' },
    { id: 20, name: 'India' },
    { id: 88, name: 'Canada' }
];

console.log(emp.filter(e => e.id == 20) ) 
//output - [ { id: 20, name: 'USA' }, { id: 20, name: 'India' } ]

console.log(emp.map(e => e.name + 'new') ) 
//output - [ 'USAnew', 'UKnew', 'Australianew', 'Indianew', 'Canadanew' ]

console.log(emp.reduce((p,e) => p + e.id,0) ) //output - 208

console.log(emp.sort((a,b)=>a.id-b.id))
//output 
/*
[ { id: 20, name: 'USA' },
  { id: 20, name: 'India' },
  { id: 24, name: 'UK' },
  { id: 56, name: 'Australia' },
  { id: 88, name: 'Canada' } ]
  */

console.log(emp.sort((a,b)=>b.id-a.id))
//output
/*
[ { id: 88, name: 'Canada' },
  { id: 56, name: 'Australia' },
  { id: 24, name: 'UK' },
  { id: 20, name: 'USA' },
  { id: 20, name: 'India' } ]
  */

console.log(Math.max.apply(null, emp.map(a=>a.id))) //output - 88

console.log(Math.min.apply(null, emp.map(a=>a.id))) // output - 20

//every, foreach, some, find, findIndex
a.forEach((v,i,a)=>
{console.log('inside for' + v);
    })

// output 
/*
inside for65
inside for3
inside for4
*/

Complex problems, Simple Solutions