Categories
JavaScript Answers

How to determine if JavaScript array contains an object with an attribute that equals a given value?

To determine if JavaScript array contains an object with an attribute that equals a given value, we use the find method,.

For instance, we write

if (vendors.find((e) => e.name === "foo")) {
  //...
}

to call find with a function that checks if the name property of the objects in the vendors array has value 'foo'.

If it’s true, then the first object that matches the condition will be returned.

Categories
JavaScript Answers

How to sort an array of integers with JavaScript?

To sort an array of integers with JavaScript, we call the sort method.

For instance, we write

const numArray = [140000, 104, 99];
const sortedNumArray = numArray.sort((a, b) => {
  return a - b;
});

to call sort with a callback that returns a - b to sort the `numArray entries in ascending order in a new array and return it.

Categories
JavaScript Answers

How to extend an existing JavaScript array with another array, without creating a new array?

To extend an existing JavaScript array with another array, without creating a new array, we call the push method.

For instance, we write

const a = [1, 2];
const b = [3, 4, 5];
a.push(...b);

to call a.push with the items in b as arguments to append the items in b into a in the order they’re listed.

We use the spread operator to call push with the entries in b as arguments.

Categories
JavaScript Answers

How to create a two dimensional array in JavaScript?

To create a two dimensional array in JavaScript, we put arrays inside an array.

For instance, we write

const items = [
  [1, 2],
  [3, 4],
  [5, 6],
];
console.log(items[0][0]);
console.log(items[0][1]);
console.log(items[1][0]);
console.log(items[1][1]);

to put arrays inside the items array.

Then we access the first array in item‘s items with

console.log(items[0][0]);
console.log(items[0][1]);

We access the 2nd array in item‘s items with

console.log(items[1][0]);
console.log(items[1][1]);
Categories
JavaScript Answers

How to find the sum of an array of numbers with JavaScript?

To find the sum of an array of numbers with JavaScript, we call the reduce method.

For instance we write

const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0);
console.log(sum);

to call reduce with a function that returns the partialSum plus the number a in the array being looped through.

We set the initial value of partialSum to 0 with the 2nd argument.

The sum is returned and it’s 6.