簡體   English   中英

返回一個數組,該數組包含:一個第一項,兩個第二項,樹第三項等,使用循環

[英]Returns an array that consists of: one first item, two second items, tree third items etc. withour using loops

我做一個分配,要求給定數組轉換為新數組,以便新數組由一個第一項,兩個第二項,樹的第三項等組成, 而無需使用循環 ,而僅使用數組特定方法。 例如:

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

您可以使用即將到來的Array#flatMap ,它是一個映射函數,用於平整數組值的第一級。

這實際上僅在Chrome或FF中有效(請參閱瀏覽器兼容性 )。

 const theFn = array => array.flatMap((v, i) => Array.from({ length: i + 1 }).fill(v)); console.log(theFn([1, 2, 3, null])); 

您可以使用Array.reduce()並使用索引和值來創建一個具有指定長度的新數組,並為每個項目填充所需的值,然后使用Array.push()和spread操作符將它們​​全部合並為一個數組,像這樣:

 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)); 

 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)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM