我做一个分配,要求将给定数组转换为新数组,以便新数组由一个第一项,两个第二项,树的第三项等组成,而无需使用循环,而仅是数组特定的方法。例如:

[] => []
[ 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);
        }
    }
}


感觉应该有更好的方法可以做到这一点。

最佳答案

一种选择是使用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 ]));

关于javascript - 返回一个数组,该数组包含:一个第一项,两个第二项,树第三项等,使用循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53186724/

10-12 12:56
查看更多