Home > Software design >  Fill an array with consecutive numbers
Fill an array with consecutive numbers

Time:01-28

I have an array that looks like this: [[3, Apple], [4, Banana], [7, Orange], [9, Pear]]

Now I'd like to add all missing numbers from 1 to 10 with empty entries where I have the fruit in the example, so that as result I'd have:

[
  [1, ],
  [2, ],
  [3, Apple],
  [4, Banana],
  [5, ],
  [6, ],
  [7, Orange],
  [8, ],
  [9, Pear]
  [10, ]
]

I'd share what I've tried so far, but I really am stuck at the beginning. Has anybody an idea how to accomplish that?

CodePudding user response:

You can start by creating an array with indexes only, and then iterate over your data to fill in the missing values from your input.

const data = [[3, "Apple"], [4, "Banana"], [7, "Orange"], [9, "Pear"]]

const result = data.reduce((result, [id, val]) => {
  result[id - 1].push(val);
  return result;
}, Array.from({length: 10}, (_, i)=> [i   1]))

console.log(result);

Here 2nd argument of the reduce function is an array of length 10, filled with 1 element arrays, where element is an index 1.

The first argument is a function called on every element of your input data, that modifies the 2nd argument.

CodePudding user response:

let result = []
let fruits = [[3, 'Apple'], [4, 'Banana'], [7, 'Orange'], [9, 'Pear']]

let fruitsObject = Object.fromEntries(fruits)

for (let i = 1; i<=10; i  ){


    result.push(fruitsObject[i] ? [i, fruitsObject[i]] : [i]) 
}

console.log(result)
  •  Tags:  
  • Related