返回一个数组,该数组包含:一个第一项,两个第二项,树第三项等,使用循环

时间:2018-11-07 09:33:45

标签: javascript arraylist

我正在执行一项任务,要求将给定数组转换为新数组,以便新数组由一个第一项,两个第二项,树的第三项等组成。不使用循环,仅针对数组方法。例如:

[] => []
[ 1 ] => [ 1 ]
[ 'a', 'b' ] => [ 'a', 'b','b' ]
[ 'a', 'b', 'c', null ] => [ 'a', 'b','b', 'c','c','c',  null,null,null,null ]

我已经通过使用.map和递归解决了它。函数看起来像这样:

function propagateItemsByPositionIndex(arr) {
    let newArray = [];
    let additions = 0;
    arr.map(function (k, x) {
        createArray(k, x);
        additions = 0;
    });
    return newArray
    function createArray(item, count) {
        if (additions <= count) {
            newArray.push(item);
            ++additions
            createArray(item, count);
        }
    }
}

感觉应该有更好的方法。

4 个答案:

答案 0 :(得分:2)

一个选择是使用reduce,并将concat用于数组累加器,该数组包含重复项i + 1重复的迭代项,其中i是该项的索引:

const transform = arr => arr.reduce((a, item, i) => (
  a.concat(Array.from(
    { length: i + 1 },
    () => item
  ))
), []);

console.log(transform([]));
console.log(transform([1]));
console.log(transform(['a', 'b']));
console.log(transform([ 'a', 'b', 'c', null ]));

答案 1 :(得分:1)

您可以使用即将到来的Array#flatMap,它是一种映射函数,可以平整数组值的第一级。

这实际上仅在Chrome或FF中有效(请参见Browser compatibility)。

const theFn = array => array.flatMap((v, i) => Array.from({ length: i + 1 }).fill(v));

console.log(theFn([1, 2, 3, null]));

答案 2 :(得分:0)

您可以使用Array.reduce()并使用索引和值来创建具有指定长度并为每个项目填充所需值的新数组,然后使用Array.push()和散点运算符将它们合并全部分成一个数组,如下所示:

arr0 = [];
arr1 = [1];
arr2 = ['a', 'b'];
arr3 = ['a', 'b', 'c', null];

function propagateItemsByPositionIndex(arr) {
  if (arr.length == 0 || arr.length == 1) return arr;
  return arr.reduce((acc, v, i) => {
    acc.push(...Array(i + 1).fill(v));
    return acc;
  }, []);
}

console.log(propagateItemsByPositionIndex(arr0));
console.log(propagateItemsByPositionIndex(arr1));
console.log(propagateItemsByPositionIndex(arr2));
console.log(propagateItemsByPositionIndex(arr3));

答案 3 :(得分:0)

let array1 = [ 1 ] 
let array2 =  [ 'a', 'b' ]
let array3 = [ 'a', 'b', 'c', null ] 

let array = [ 'a', 'b' ]

function transformArray(array){
  return array.reduce(
    (acc, curr, idx)=>{
      //Creating an array of length equal to index+1 
      [...Array(idx+1)].forEach(item => acc[acc.length] = curr)
      return acc
    },
   []
  )
}
console.log(transformArray(array1))
console.log(transformArray(array2))
console.log(transformArray(array3))