简体   繁体   中英

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

Im doing an assignment that requires that given array be converted to new one so that new array consists of one first item, two second items, tree third items etc. without using loops , just array specific methods. For example:

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

I have solved it by using .map and recursions. Function looks like this:

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

It feels like there should be much better way to do this.

One option is to use reduce , and concat to the array accumulator an array consisting of the iterated item repeated i + 1 times, where i is the item's index:

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

You could use the upcoming Array#flatMap , which is a mapping function and flats the first level of the array values.

This works actually only in Chrome or FF (see Browser compatibility ).

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

You can use Array.reduce() and use the index and value to create a new array with the specified length and filled with the desired value for each item, then use Array.push() and the spread operator to merge them all into one array, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM