Categories
JavaScript Answers

How to filter an array from all elements of another array with JavaScript?

To filter an array from all elements of another array with JavaScript, we use the filter and includes methods.

For instance, we write

const arr1 = [1, 2, 3, 4];
const arr2 = [2, 4];
const res = arr1.filter((item) => !arr2.includes(item));
console.log(res);

to call filter with a callback that checks if the item in arr1 isn’t in arr2.

If it’s not, then it’s included in the array returned by filter.

Categories
JavaScript Answers

How to get the last 5 elements, excluding the first element from an array with JavaScript?

To get the last 5 elements, excluding the first element from an array with JavaScript, we call the Math.max and slice methods.

For instance, we write

arr.slice(Math.max(arr.length - 5, 0));

to call Math.max with arr.length - 5 and 0 to return the max number between the 2 numbers.

And then we call slice to return an array with the arr entries between the index returned by max to the last element.

Categories
JavaScript Answers

How to search in array of object in JavaScript MongoDB?

To search in array of object in JavaScript MongoDB, we use the $elemMatch property.

For instance, we write

db.users.find({
  awards: { $elemMatch: { award: "National Medal", year: 1975 } },
});

to call find with an object that has awars.$elemMatch set to an object with the field values we’re looking for to get the values in the awards array field that has the property values listed.

Categories
JavaScript Answers

How to swap array elements with JavaScript?

To swap array elements with JavaScript, we use destructuring.

For instance, we write

[arr[0], arr[1]] = [arr[1], arr[0]];

to ass arr[1] to arr[0]and assignarr[0]toarr[1]` with destructuring.

Categories
JavaScript Answers

How to loop through an array containing objects and access their properties with JavaScript?

To loop through an array containing objects and access their properties with JavaScript, we use the forEach method.

For instance, we write

yourArray.forEach((arrayItem) => {
  const x = arrayItem.prop + 2;
  console.log(x);
});

to call forEach with a callback that gets the prop property value from the arrayItem being looped through.

And then we add 2 to it assign the sum to x.