Categories
JavaScript Answers

How to check if an array item is set in JavaScript?

To check if an array item is set in JavaScript, we use the in operator.

For instance, we write

const assocPagine = {
  home: 0,
  about: 1,
  work: 2,
};

if ("work" in assocPagine) {
  // ...
}

to check if the work property is in the assocPagine object as a property in the object itself or as an inherited property.

Categories
JavaScript Answers

How to replace a string in a JavaScript array?

To replace a string in a JavaScript array, we use the array map and string replaace methods.

For instance, we write

const resultArr = arr.map((x) => {
  return x.replace(/,/g, "");
});

to call arr.map with a callback that returns a new string that replace commas in x with empty strings with replace.

A new array with the replacements done is returned.

Categories
JavaScript Answers

How to count the number of true values in an array of boolean values with JavaScript?

To count the number of true values in an array of boolean values with JavaScript, we call the filter method.

For instance, we write

const arr = [true, false, true, false, true];
const count = arr.filter(Boolean).length;

to call arr.filter with Boolean to return an array with the truthy values in arr in a new array.

Then we get the count of that with the length property.

Categories
JavaScript Answers

How to search for an object in an array of objects with JavaScript?

To search for an object in an array of objects with JavaScript, we use the array some method.

For instance, we write

const listOfObjecs = [
  { id: 1, name: "Name 1", score: 11 },
  { id: 2, name: "Name 2", score: 22 },
  { id: 3, name: "Name 3", score: 33 },
  { id: 4, name: "Name 4", score: 44 },
  { id: 5, name: "Name 5", score: 55 },
];

const object = { id: 3, name: "Name 3", score: 33 };
const booleanValue = listOfObjecs.some(
  (item) =>
    item.id === object.id &&
    item.name === object.name &&
    item.score === object.score
);

to call listOfObjects.some with a callback that checks if the id property of each item in listOfObjects equals object.id.

And we do the same with the name and score properties and combine the expressions with logical and.

Since the object that meets this condition exists in listOfObjects, true is returned.

Categories
JavaScript Answers

How to store an array of objects in local storage with JavaScript?

To store an array of objects in local storage with JavaScript, we convert it to a JSON string.

For instance, we write

localStorage.setItem("users", JSON.stringify(users));

to call JSON.stringify with the users array to convert it into a JSON string.

Then we call setItem to store the string as the value with key 'users'.