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.

Categories
JavaScript Answers

How to remove item from array using its name / value with JavaScript?

To remove item from array using its name / value with JavaScript, we use the filter method.

For instance, we write

const COUNTRY_ID = "AL";

countries.results = countries.results.filter((el) => {
  return el.id !== COUNTRY_ID;
});

to call filter with a callback to return an array within the countries.results array without the object with id not equal to COUNTRY_ID.

Categories
JavaScript Answers

How to search array of arrays with JavaScript?

To search array of arrays with JavaScript, we use the array some and every methods.

For instance, we write

const ar = [
  [2, 6, 89, 45],
  [3, 566, 23, 79],
  [434, 677, 9, 23],
];

const val = [3, 566, 23, 79];

const bool = ar.some((arr) => {
  return arr.every((prop, index) => {
    return val[index] === prop;
  });
});

to call some with a callback that searches every element of the nested array to check if they’re equal with every.

We call every with a callback that check the index of arr to see if it’s equal to prop in the nested array.