简体   繁体   中英

How to add an array of elements in order?

I have an array: const arr = [1, 2, 5, 10] ;

How I can transform it to const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ?;

A simple way to do it without hard-coding the number of iterations is to get the minimum value from the array and the maximum and then fill the numbers in-between them.

Here's one way to do it

 const arr = [1, 2, 5, 10]; var highest = Math.max(...arr); var minimum = Math.min(...arr); var output = []; for(var i = minimum; i <= highest; i++){ output.push(i); } console.log(output); 

Here's a one liner solution based on Adriani6 answer:

 const arr = [1, 2, 5, 10]; var highest = Math.max(...arr); var minimum = Math.min(...arr); const newArr = ([...Array(highest+1).keys()]).slice(minimum); console.log(newArr); 

You could take a nested while statement and splice missing items.

 var array = [1, 2, 5, 10], i = array.length; while (i--) while (array[i - 1] + 1 < array[i]) array.splice(i, 0, array[i] - 1); console.log(...array); 

const arr = [1, 2, 5, 10];

for(let i = 1; i <= 10; i++) { // Loop from 1 till 10, including 10
    if (!arr.includes(i)) { // If arr does not include 'i'
        arr.splice(i - 1, 0, i); // We insert it into the array
        // -1, because arrays start at 0
    }
}

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