最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Array mapping - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Nov 22, 2016 at 12:23 RanjithRanjith 2,8193 gold badges24 silver badges42 bronze badges 7
  • use indexof and push into arr – Mahi Commented Nov 22, 2016 at 12:25
  • filter checking for the index once to get selectedArr, then filter NOT-ting the previous predicate for availArr? – VLAZ Commented Nov 22, 2016 at 12:27
  • I can use indexOf for populating selectedArr. What about availArr? – Ranjith Commented Nov 22, 2016 at 12:27
  • 1 @Guedes that is more suited for sequential elements, OP wants alternating. – VLAZ Commented Nov 22, 2016 at 12:28
  • 2 splice is even more insteresting – mplungjan Commented Nov 22, 2016 at 12:28
 |  Show 2 more ments

8 Answers 8

Reset to default 5

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.

You could use Array#reduceRight and iterate the indices array.

var defaultArr = ['a', 'b', 'c', 'd'],
    availArr = defaultArr.slice(),
    selectedArr = [],
    indices = [0, 2];

indices.reduceRight(function (_, a) {
    selectedArr.unshift(availArr.splice(a, 1)[0]);
}, 0);

console.log(availArr);
console.log(selectedArr);

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


function splitArray(indexes) {
  availArr = defaultArr; 
  indexes.forEach(function(idx) {
    let item = availArr.splice(idx, 1)[0];
    selectedArr.push(item);
  })
}

splitArray([0, 2]);

console.log(availArr);
console.log(selectedArr);

You can use Array methods like forEach and includes

var given = ['a', 'b', 'c', 'd'];
var indexes = [0, 2];
var available = [];
var selected = [];

given.forEach(function (v, i) {
  if (indexes.includes(i)) {
    selected.push(v);
  } else {
    available.push(v);
  }
});

document.write(JSON.stringify({
  given: given,
  available: available,
  selected: selected
}));

In JS Array.prototype.reduceRight() is the ideal functor to iterate over an array and to morph it by removing items. Accordingly i would approach this job as follows;

var defaultArr = ['a', 'b', 'c', 'd'],
       indices = [0, 2];
        result = defaultArr.reduceRight((p,c,i,a) => indices.includes(i) ? p.concat(a.splice(i,1)) : p ,[]);
console.log(defaultArr,result);

You can use array.splice + array.concat to achieve this

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

function parseIndexes(indexArr){
  var deleteCount = 0;
  availArr = defaultArr.map(x=>x);
  indexArr.forEach(function(i){
    selectedArr = selectedArr.concat(availArr.splice(i-deleteCount,1))
    deleteCount++;
  });   
  console.log(availArr, selectedArr)
}

parseIndexes([0,2])

With only Array.filter

var array = ['a', 'b', 'c', 'd'];
var indexes = [0, 2]
array.filter(function(el, i) { 
    return indexes.indexOf(i) !== -1 
});

// ["a", "c"]

With array the array of your elements, objects, strings... and indexes the array containing all the indexes of the elements you want to keep, you just remove from the arrayarray all the elements whose id isn't in theindexes array.

The array of all selected entries can be obtained in one line via the Array.map:

var defaultArr = ['a', 'b', 'c', 'd']
var index = [0,2]
var selectedArr = index.map(i => defaultArr[i]) //=> ['a', 'c']

Then the array of the remaining entries can be retrieved e.g. with the Ramda's difference operator:

var availArr = R.difference(defaultArr, selectedArr) //=> ['b', 'd']
发布评论

评论列表(0)

  1. 暂无评论