Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!