Ranjith Ranjith - 15 days ago 7
Javascript Question

JavaScript Array mapping

Consider the following scenario;

var defaultArr = ['a', 'b', 'c', 'd'];
var availArr = [];
var selectedArr = [];


If I am passing array some
index
's value in param's, I need to split up my array's

Example:

If Array Index :
0,2


Expected result:

availArr = ['b', 'd'];
selectedArr = ['a', 'c'];


Is there any default method to achieve this?

Answer

Failrly easy with Array.reduce

var defaultArr = ['a', 'b', 'c', 'd'];
var indexes = [0,2];

var result = defaultArr.reduce(function(p, c, i){
  if(indexes.indexOf(i)>-1)
    p.selectedArr.push(c);
  else
    p.availArr.push(c);
  return p;
}, {availArr: [], selectedArr:[]});;


console.log('availArr',result.availArr);
console.log('selectedArr',result.selectedArr);

This works because reduce takes a callback argument which is passed 3 arguments - in my example above

  • p the seed object passed in
  • c the current array element
  • i the index of the current element

And uses that information along with indexOf to determine which result array to push to.