Categories
JavaScript Answers

How to change value of object which is inside an array using JavaScript?

To change value of object which is inside an array using JavaScript, we use findIndex to find the item.

For instance, we write

const myArray = [
  { id: 0, name: "John" },
  { id: 1, name: "Sara" },
  { id: 2, name: "Domnic" },
  { id: 3, name: "Bravo" },
];

const objIndex = myArray.findIndex((obj) => obj.id == 1);
myArray[objIndex].name = "Bob";

to call findIndex to find index of the object in myArray with id 1.

Then we use the index to get the item from myArray and assign its name property to 'Bob'.

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.