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.

Categories
JavaScript Answers

How to get list of duplicate objects in an array of objects with JavaScript?

To get list of duplicate objects in an array of objects with JavaScript, we use some array methods.

For instance, we write

const srr = [
  { id: 10, name: "someName1" },
  { id: 10, name: "someName2" },
  { id: 11, name: "someName3" },
  { id: 12, name: "someName4" },
];

const unique = arr
  .map((e) => e.id)
  .map((e, i, final) => final.indexOf(e) === i && i)
  .filter((obj) => arr[obj])
  .map((e) => arr[e]);

to call arr.map with a callback to return an array of id property values.

Then we call map with a callback to get the index of the id value in.

And then we call filter to get the first instance of the object with the given id in arr with filter.

Categories
JavaScript Answers

How to delete an item from Redux state with JavaScript?

To delete an item from Redux state with JavaScript, we can use the array filter method.

For instance, we write

export const commentList = (state, action) => {
  switch (action.type) {
    //...
    case "DELETE_COMMENT":
      return state.filter(({ id }) => id !== action.data);
    //...
  }
};

to call state.filter to return an array without the object with the id property equal the action.data property.

The returned array will be the new value of the state.

Categories
JavaScript Answers

How to add spaces between array items in JavaScript?

To add spaces between array items in JavaScript, we use the join method.

For instance, we write

const showtimes = ["1pm", "2pm", "3pm"];
const showtimesAsString = showtimes.join(", ");

to call showtimes.join with ', ' as the delimiter between each string in showtimes.

Therefore, showtimesAsString is "1pm, 2pm, 3pm".