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.

Categories
JavaScript Answers

How to convert a JavaScript array to a set?

To convert a JavaScript array to a set, we use the Set constructor.

For instance, we write

const arr = [55, 44, 65];
const set = new Set(arr);

to convert the arr array into a set with the Set constructor.

Categories
JavaScript Answers

How to create an array of object literals in a loop with JavaScript?

To create an array of object literals in a loop with JavaScript, we use the map method.

For instance, we write

const arr = oFullResponse.results.map((obj) => ({
  key: obj.label,
  sortable: true,
  resizeable: true,
}));

to call oFullResponse.results.map with a callback that returns an object with the properties and return an array with the objects returned by the map callback.

Categories
JavaScript Answers

How to check if object value exists within a JavaScript array of objects and if not add a new object to array?

To check if object value exists within a JavaScript array of objects and if not add a new object to array, we use the some method.

For instance, we write

const arr = [
  { id: 1, username: "fred" },
  { id: 2, username: "bill" },
  { id: 3, username: "ted" },
];

const add = (arr, name) => {
  const { length } = arr;
  const id = length + 1;
  const found = arr.some((el) => el.username === name);
  if (!found) {
    arr.push({ id, username: name });
  }
  return arr;
};

console.log(add(arr, "ted"));

to define the add function.

Then we check if the entry with username equal to name exists with some.

If it returns false, then we call arr.push to append the object into the arr array.