Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 771
Ranjith Avatar asked Dec 04 '22 23:12

Ranjith


1 Answers

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.

like image 109
Jamiec Avatar answered Jan 02 '23 05:01

Jamiec