Categories
JavaScript Answers

How to find the largest number contained in a JavaScript array?

To find the largest number contained in a JavaScript array, we use the Math.max method and the spread operator.

For instance, we write

const arr = [1, 2, 3];
const max = Math.max(...arr);

to call Math.max with the entries in the arr array as arguments.

We use the spread operator to spread the entries as arguments.

Categories
JavaScript Answers

How to search and remove string within a JavaScript array?

To search and remove string within a JavaScript array, we use the filter method.

For instance, we write

const arr = ["A", "B", "C"];
const filteredArr = arr.filter((e) => e !== "B");

to call arr.filter to return an array without 'B' in it.

Categories
JavaScript Answers

How to find the array index with a value with JavaScript?

To find the array index with a value with JavaScript, we use the indexOf method.

For instance, we write

const imageList = [100, 200, 300, 400, 500];
const index = imageList.indexOf(200);

to call imageList.indexOf with 200 to return the first index of 200 in the imageList array.

Categories
JavaScript Answers

How to define an array with conditional elements with JavaScript?

To define an array with conditional elements with JavaScript, we use the ternary operator.

For instance, we write

const items = ["foo", ...(true ? ["bar"] : []), ...(false ? ["falsy"] : [])];

console.log(items);

to spread the entries in ["bar"] since the condition is true.

And we spread the empty array into the array since false is before the 2nd ternary operator.

Categories
JavaScript Answers

How to call JavaScript reduce() on an object?

To call JavaScript reduce() on an object, we can use the Object.values method.

For instance, we write

const o = {
  a: { value: 1 },
  b: { value: 2 },
  c: { value: 3 },
};

Object.values(o).reduce((previous, entry) => {
  return previous + entry.value;
}, 0);

to call Object.values with o to return an array of object property values in o.

Then we call reduce with a callback that returns the sum of the previous partial sum plus the entry.value value.

entry is the o property value being looped through.