Looping numbers with object values and push output to an array - JavaScript?

In JavaScript, you can create an array from an object by mapping object values to specific positions using Array.from(). This technique is useful when you have sparse data that needs to be converted into a dense array format.

Problem Overview

Given an object with numeric keys and values, we want to create an array where the object values are placed at positions corresponding to their keys, filling missing positions with a default value.

var numberObject = { 2: 90, 6: 98 };
console.log("The original object:");
console.log(numberObject);
The original object:
{ '2': 90, '6': 98 }

Using Array.from() Method

The Array.from() method creates a new array instance from an array-like object. We can use it with a length property and a mapping function to fill positions based on object keys.

var numberObject = { 2: 90, 6: 98 };

// Create array of length 15, mapping object values to positions
var fillThePositionValue = Array.from({length: 15}, (value, index) => 
    numberObject[index + 1] || "novalue"
);

console.log("After filling positions with object values:");
console.log(fillThePositionValue);
After filling positions with object values:
[
  'novalue', 90,
  'novalue', 'novalue',
  'novalue', 98,
  'novalue', 'novalue',
  'novalue', 'novalue',
  'novalue', 'novalue',
  'novalue', 'novalue',
  'novalue'
]

How It Works

The Array.from() method takes two parameters:

  • Array-like object: {length: 15} defines the array size
  • Mapping function: (value, index) => numberObject[index + 1] || "novalue" checks if the object has a value at position index + 1

The index + 1 is used because array indices start at 0, but our object keys start at 1.

Alternative Approach

You can also use different default values or modify the logic:

var numberObject = { 2: 90, 6: 98 };

// Using null as default value
var result = Array.from({length: 10}, (_, index) => 
    numberObject[index + 1] ?? null
);

console.log("With null as default:");
console.log(result);
With null as default:
[
  null, 90, null,
  null, null, 98,
  null, null, null,
  null
]

Conclusion

The Array.from() method provides an elegant solution for converting sparse object data into dense arrays. This technique is particularly useful when you need to align data with specific positions or indices.

Updated on: 2026-03-15T23:19:00+05:30

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements