Categories
JavaScript Answers

How to find out how many times an array element appears with JavaScript?

To find out how many times an array element appears with JavaScript, we use the filter method.

For instance, we write

const countInArray = (array, what) => {
  return array.filter((item) => item == what).length;
};

to define the countInArray function.

In it, we get the count the number of items equal to what by calling array.filter with a callback that returns if item equals to what to return an array with entries with what inside.

Then we get the length property to get the count of what in the array returned by filter.

Categories
JavaScript Answers

How to update the attribute value of an object using the map function in JavaScript?

To update the attribute value of an object using the map function in JavaScript, we return the updated object.

For instance, we write

const editSchoolName = (schools, oldName, name) =>
  schools.map((item) => {
    if (item.name === oldName) {
      return { ...item, name };
    } else {
      return item;
    }
  });

to define the editSchooName function that returns a new version of the schools array that has entries mapped from schools with the objects updated if they have name property equal to oldName.

Categories
JavaScript Answers

How to move to prev/next element of an array with JavaScript?

To move to prev/next element of an array with JavaScript, we can define our own array class.

For instance, we write

class TraversableArray extends Array {
  next() {
    return this[++this.current];
  }
}

to define the TraversableArray class that extends the Array class.

In it, we add the next method that returns the object at the current index after incrementing it by 1.

Categories
JavaScript Answers

How to find if object property exists in an array with Lodash and JavaScript?

To find if object property exists in an array with Lodash and JavaScript, we use the has method.

For instance, we write

const countries = { country: { name: "France" } };
const isExist = _.has(countries, "country.name");

to call has with the countries object and the property to look for in each object.

Therefore, isExist is true since country.name is in the countries object.

Categories
JavaScript Answers

How to alert an array with JavaScript?

To alert an array with JavaScript, we convert it to a string before calling alert.

For instance, we write

alert(JSON.stringify(aCustomers));

to call JSON.stringify to convert the aCustomers array to a JSON array string.

Then we call alery with the string to show an alert box with the array string.