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.

Categories
JavaScript Answers

How to find and update values in an array of objects in JavaScript?

To find and update values in an array of objects in JavaScript, we use the map method.

For instance, we write

const updatedData = originalData.map((x) =>
  x.id === id ? { ...x, updatedField: 1 } : x
);

to call originalData.map with a callback that returns the new object if x.id equals id and x otherwise.

An array with the objects returned by the map callback is returned by map.

Categories
JavaScript Answers

How to get the closest number out of an array with JavaScript?

To get the closest number out of an array with JavaScript, we use the reduce method.

For instance, we write

const counts = [4, 9, 15, 6, 2];
const goal = 5;

const closest = counts.reduce((prev, curr) => {
  return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
});

console.log(closest);

to call counts.reduce with a callback that checks if curr - goal is smaller than prev - goal in absolute value.

If it is, we return curr.

Otherwise, prev is `returned.