logo

Creating an Array of N Numbers

During a coding test, I wanted to create an array of N numbers and use forEach.

While I could have used a simple for or while loop, I was more comfortable using array methods, so I started searching for a suitable method.

1D Array (Array of N numbers)

  1. for loop
function createArray(n) {
  const result = []
  for (let i = 1; i <= n; i++) {
    result.push(i)
  }
  return result
}
  1. while loop
function createArray(n) {
  const result = []
  let i = 1

  while (i <= n) {
    result.push(i)
    i++
  }

  return result
}
  1. Array.from
//* Recommend
const array = Array.from({ length: n }, (_, i) => i + 1)
  1. Array.map
const array = Array(n)
  .fill()
  .map((_, i) => i + 1)

Creating a 2D Array, e.g. [[1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5]]

2 minutes to read

Sorting an Object Using Map

While arrays can easily be sorted in ascending or descending order using the sort method, how can we sort objects by their values?

Here’s one approach:

  1. Convert the object into an array for sorting.

  2. Sort the array by the object’s values.

  3. Convert the sorted array back into an object. If order needs to be maintained, use a Map.

const const fruitCounts = { apple: 10, banana: 2, orange: 7, mango: 5 };

const sortedByValue = Object.entries(fruitCounts)
    .sort(([, a], [, b]) => a - b);

console.log(sortedByValue); 
// Output: [ [ 'banana', 2 ], [ 'mango', 5 ], [ 'orange', 7 ], [ 'apple', 10 ] ]

// Convert to Map to maintain order
const sortedMap = new Map(sortedByValue);

console.log(sortedMap);
// Output: Map {'banana' => 2, 'mango' => 5, 'orange' => 7, 'apple' => 10}

console.log(Array.from(sortedMap))
// Converting back to the sorted array

for(const [key, value] of sortedMap){
    console.log(`${key}: ${value}`)
}
// Iterate with for...of to handle keys and values.
One minute to read