Categories
JavaScript Answers

How to declare an empty two-dimensional array in JavaScript?

To declare an empty two-dimensional array in JavaScript, we use the map method.

For instance, we write

const arr = [...Array(3)].map(() => Array(5));

to create an array with 3 empty slots with Array(3).

And then we spread them to a new array.

Then we call map with a callback that returns an array with 5 empty slots created with Array(5).

We now have a 3×5 empty 2d array.

Categories
JavaScript Answers

How to remove duplicate form an array with JavaScript?

To remove duplicate form an array with JavaScript, we can create a set.

For instance, we write

const array = [
  { id: 123, value: "value1", name: "Name1" },
  { id: 124, value: "value2", name: "Name1" },
  { id: 125, value: "value3", name: "Name2" },
  { id: 126, value: "value4", name: "Name2" },
];
const names = [...new Set(array.map((a) => a.name))];

console.log(names);

to call map to return an array of name property values from the objects in array.

Then we convert it to a set with the Set constructor.

Then we use the spread operator to convert the set into an array.

Categories
JavaScript Answers

How to split a JavaScript array into N arrays?

To split a JavaScript array into N arrays, we can use the splice method.

For instance, we write

const split = (array, n) => {
  const [...arr] = array;
  const res = [];
  while (arr.length) {
    res.push(arr.splice(0, n));
  }
  return res;
};

to define the split function.

In it, we make a copy of array with the rest operator.

And then we use a while loop that calls arr.splice to remove the items from index 0 to n - 1 from arr and return them in an array.

Then we call res.push to append the array into res.

This is done until arr is empty.

Categories
JavaScript Answers

How to loop through files in a folder with Node.js?

To loop through files in a folder with Node.js, we use the opendir method.

For instance, we write

const fs = require("fs");

const ls = async (path) => {
  const dir = await fs.promises.opendir(path);
  for await (const dirent of dir) {
    console.log(dirent.name);
  }
};

to call the opendir method with the folder path to return a promise with the items in the folder.

Then we use the for-await-of loop to loop through all the items in the folder.

Categories
JavaScript Answers

How to obtain smallest value from array in JavaScript?

To obtain smallest value from array in JavaScript, we use the Math.min method.

For instance, we write

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4];
const min = Math.min(...arr);

to call Math.min with the entries in the arr array as arguments to get the min number from the arr array and return it.

We use the spread operator to spread the arr values as arguments.