Categories
JavaScript Answers

How to perform .join on value in array of objects with JavaScript?

To perform .join on value in array of objects with JavaScript, we use map to map the array of object to an array of primitive values.

For instance, we write

const users = [
  { name: "Joe", age: 22 },
  { name: "Kevin", age: 24 },
  { name: "Peter", age: 21 },
];
const s = users.map((u) => u.name).join(", ");

to call users.map with a callback that gets the name property value from each object and return them in an array.

Then we call join to combine then into a string with commas.

Categories
JavaScript Answers

How to remove all elements contained in another array with JavaScript?

To remove all elements contained in another array with JavaScript, we use the filter and includes method.

For instance, we write

const myArray = ["a", "b", "c", "d", "e", "f", "g"];
const toRemove = ["b", "c", "g"];
const newArray = myArray.filter((el) => {
  return !toRemove.includes(el);
});

to call myArray.filter with a callback that calls toRemove.includes with the el element being iterator through to return an array with the myArray entries that aren’t in toRemove.

Categories
JavaScript Answers

How to add an object to an array with JavaScript?

To add an object to an array with JavaScript, we call the push method.

For instance, we write

const a = [];
const b = {};
a.push(b);

to call a.push with b to append b as the last element of a.

Categories
JavaScript Answers

How to remove first element from an array in JavaScript?

To remove element from an array in JavaScript, we use the shift method.

For instance, we write

const array = [1, 2, 3, 4, 5];
array.shift();

to call array.shift to remove the first element of array in place.

Categories
JavaScript Answers

How to get the first element of an array with JavaScript?

To get the first element of an array with JavaScript, we use index 0.

For instance, we write

const array = ["first", "second", "third", "fourth", "fifth"];
alert(array[0]);

to get the first entry of array with array[0].