Categories
JavaScript Answers

How to search for a string inside an array of strings with JavaScript?

To search for a string inside an array of strings with JavaScript, we use the find method.

For instance, we write

const strs = ["abc", "def", "ghi", "jkl", "mno"];
const value = "abc";
const str = strs.find((str) => str === value);

to call strs.find with a callback that checks if str in strs is equal to value.

If there is such an entry, then the first instance of str is returned.

Categories
JavaScript Answers

How to get the size of an array in an object with JavaScript?

To get the size of an array in an object with JavaScript, we use the length property.

For instance, we write

const st = {
  itemA: {},
  itemB: [
    { id: "s01", cd: "c01", dd: "d01" },
    { id: "s02", cd: "c02", dd: "d02" },
  ],
};

console.log(st.itemB.length);

to get the length of the st.itemB array property with st.itemB.length.

Categories
JavaScript Answers

How to find length or size of an array in JavaScript?

To find length or size of an array in JavaScript, we use the length property.

For instance, we write

const arr = [];
arr[1] = 2;
arr[2] = 3;
console.log(arr.length);

to create the array arr.

Then we get its size with arr.length.

Categories
JavaScript Answers

How to remove array element by value with JavaScript?

To remove array element by value with JavaScript. we use the indexOf and splice methods.

For instance, we write

const arr = ["orange", "red", "black", "white"];
const index = arr.indexOf("red");
if (index >= 0) {
  arr.splice(index, 1);
}

to call arr.indexOf to get the index of the first instance of 'red' in arr.

Then we check if index is bigger than 0 to check if it’s found.

If it is, then we call splice with index and 1 to return the item in arr at index.

Categories
JavaScript Answers

How to flatten an array of arrays of objects with JavaScript?

To flatten an array of arrays of objects with JavaScript, we use the flat method.

For instance, we write

const flattened = [["object1"], ["object2"]].flat();

to return a flattened version of the [["object1"], ["object2"]] array with flat.