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".

Categories
JavaScript Answers

How to find missing numbers in a sequence with JavaScript?

To find missing numbers in a sequence with JavaScript, we use a for loop.

For instance, we write

for (let i = 1; i < numArray.length; i++) {
  if (numArray[i] - numArray[i - 1] !== 1) {
    //...
  }
}

to loop through the sorted array numArray with a for loop.

In it, we check if the current number being looped through numArray[i] is 1 less than the previous number numArray[i - 1] by subtracting them and see if the difference is 1.

If it’s not, then the numbers in between the 2 numbers are missing.

Categories
JavaScript Answers

How to convert string to array of object in JavaScript?

To convert string to array of object in JavaScript, we use the JSON.parse method.

For instance, we write

const jsonString = '{ "a": 1, "b": 2 }';
const myObject = JSON.parse(jsonString);

to call JSON.parse with jsonString to convert jsonString into an object.