Ole Rehr
Ole Rehr

Reputation: 21

Fill an array with consecutive numbers

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?

Upvotes: 0

Views: 1351

Answers (3)

A1exandr Belan
A1exandr Belan

Reputation: 4780

A kind of over-engineering way. Don't be so hard on me.

const sourceArr = [[3, 'Apple'], [4, 'Banana'], [7, 'Orange'], [9, 'Pear']];
const sourceObj = Object.fromEntries(sourceArr);
const nullArr = [...Array(10).keys()].map(i => [i+1]);
const nullObj = Object.fromEntries(nullArr);
const unionObj = { ...nullObj, ...sourceObj };
const pairs = Object.entries(unionObj)
const result = pairs.map(pair => pair.filter(e => e));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

Upvotes: 1

AmirA
AmirA

Reputation: 332

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)

Upvotes: 2

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6778

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.

Upvotes: 2

Related Questions