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.

Categories
JavaScript Answers

How to convert a string of numbers to an array of numbers?

To convert a string of numbers to an array of numbers, we use the split and map methods.

For instance, we write

const a = "1,2,3,4";
const b = a.split(",").map(Number);

to call split to split the a string into a string array by the commas.

And then we call map with Number to convert each entry to a number and return them in a new array.

Categories
JavaScript Answers

How to compute the sum and average of elements in an array with JavaScript?

To compute the sum and average of elements in an array with JavaScript, we use the reduce method.

For instance, we write

const average = (arr) => arr.reduce((p, c) => p + c, 0) / arr.length;
const result = average([4, 4, 5, 6, 6]);
console.log(result);

to define the average function that calls arr.reduce to return the sum of the entries in arr.

And we divide the sum by arr.length array length to get the average.

Then we call average to return the average of the entries in [4, 4, 5, 6, 6].

Categories
JavaScript Answers

How to get a list of associative array keys with JavaScript?

To get a list of associative array keys with JavaScript, we call the Object.keys method.

For instance, we write

const dictionary = {
  cats: [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
  dogs: [4, 5, 6, 3, 2],
};

const keys = Object.keys(dictionary);
console.log(keys);

to call Object.keys with dictionary to return a list of key strings from the dictionary object.

Categories
JavaScript Answers

How to do map and filter an array at the same time with JavaScript?

To map and filter an array at the same time with JavaScript, we use the flatMap method.

For instance, we write

const names = options.flatMap((o) => (o.assigned ? [o.name] : []));

to call options.flatMap with a callback that checks if o.assigned is set.

If it is, then we array with o.name inside.

Otherwise, we return an empty array.

And we use flatMap to combine them into one flattened array.