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.

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].