To search and remove string within a JavaScript array, we use the filter method.
For instance, we write
const arr = ["A", "B", "C"];
const filteredArr = arr.filter((e) => e !== "B");
to call arr.filter to return an array without 'B' in it.
To search and remove string within a JavaScript array, we use the filter method.
For instance, we write
const arr = ["A", "B", "C"];
const filteredArr = arr.filter((e) => e !== "B");
to call arr.filter to return an array without 'B' in it.
To find the array index with a value with JavaScript, we use the indexOf method.
For instance, we write
const imageList = [100, 200, 300, 400, 500];
const index = imageList.indexOf(200);
to call imageList.indexOf with 200 to return the first index of 200 in the imageList array.
To define an array with conditional elements with JavaScript, we use the ternary operator.
For instance, we write
const items = ["foo", ...(true ? ["bar"] : []), ...(false ? ["falsy"] : [])];
console.log(items);
to spread the entries in ["bar"] since the condition is true.
And we spread the empty array into the array since false is before the 2nd ternary operator.
To call JavaScript reduce() on an object, we can use the Object.values method.
For instance, we write
const o = {
a: { value: 1 },
b: { value: 2 },
c: { value: 3 },
};
Object.values(o).reduce((previous, entry) => {
return previous + entry.value;
}, 0);
to call Object.values with o to return an array of object property values in o.
Then we call reduce with a callback that returns the sum of the previous partial sum plus the entry.value value.
entry is the o property value being looped through.
To find and update values in an array of objects in JavaScript, we use the map method.
For instance, we write
const updatedData = originalData.map((x) =>
x.id === id ? { ...x, updatedField: 1 } : x
);
to call originalData.map with a callback that returns the new object if x.id equals id and x otherwise.
An array with the objects returned by the map callback is returned by map.