简体   繁体   中英

How can i write the following code without for loops in javascript

I need help with the following program in javascript

A function, written without any loop statements, that accepts an array and produces a new array equal to the initial array with ith element (1-based) repeated i times.

i was able to write the code in for loop, just need help in writing without loop

export function stretched(a) {
    const stretchedArray = [];
    for (let [index, item] of a.entries()) {
      for (let i = 0; i < index + 1; i++) {
        stretchedArray.push(item);
      }
    }
    return stretchedArray;
}

This can be another approach:

 function stretched(a) { const stretchedArray = []; for (let [index, item] of a.entries()) { stretchedArray.push(...(new Array(index + 1).fill(item))) } return stretchedArray; } console.log(stretched(['a','b','c']))

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