Categories
JavaScript Answers

How to select all other values in an array except the ith element with JavaScript?

To select all other values in an array except the ith element with JavaScript, we use the filter method.

For instance, we write

const items = [1, 2, 3, 4, 5, 6];
const current = 2;
const itemsWithoutCurrent = items.filter((x) => {
  return x !== current;
});

to call items.filter with a callback that checks if x isn’t equal to current and return all the elements in items where x isn’t equal to current.

Categories
JavaScript Answers

How to create a dynamic array of strings with JavaScript?

To create a dynamic array of strings with JavaScript, we just add or remove items as we want.

For instance, we write

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
myArray.push(11);
const popped = myArray.pop();

to call myArray.push with 11 to push a 11 as the last item in myArray.

And we call myArray.pop to remove the last item in myArray and return the removed item.

Categories
JavaScript Answers

How to use reduce() to find min and max values with JavaScript?

To use reduce() to find min and max values with JavaScript, we use the spread operator.

For instance, we write

const min = Math.min(...items);
const max = Math.max(...items);

to call Math.min with the values in the items array spread as arguments to get the min value in the items array.

And we call Math.max with the values in the items array spread as arguments to get the max value in the items array.

Categories
JavaScript Answers

How to set all values of an array with JavaScript?

To set all values of an array with JavaScript, we use the fill method.

For instance, we write

const arr = new Array(3).fill(9);

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

Then we call fill with 9 to fill the empty slots with 9’s.

Categories
JavaScript Answers

How to slice an object in JavaScript?

To slice an object in JavaScript, we use the Object.entries and Object.fromEntries methods.

For instance, we write

const obj = {
  0: "zero",
  1: "one",
  2: "two",
  3: "three",
  4: "four",
};
const res = Object.fromEntries(Object.entries(obj).slice(0, 4));

to call Object.entries with obj to return an array of key-value pair arrays in obj.

Then we call slice to return a slice of the key-value pair array we want.

And then we call Object.fromEntries with the sliced array to convert it back to an object.