0

The below given state is in my class component. Need to avoid adding duplicate objects in an array my state is given below

this.state = {
      frequency: {
        time: [
                {time:"20:15",timezone:"IST"},
                {time:"01:30",timezone:"UST"}
              ],
      },
    };

the requirement is sholud not add the object with same time and timezone value. my push code is given below

 this.setState((state) => ({
        ...state,
        frequency: {
          ...state.frequency,
          time: [...state.frequency.time, selecttime],
        },
        )}
     ))

the selecttime which carries the object which im going to push in the time array

const selecttime = {time:"20:15",timezone:"IST"}

i should not adding same object again. how do i avoid pushing duplicate objects in state array

1
  • 1
    use array.find to check if same entry exists, its not a react question Commented Oct 14, 2020 at 6:53

1 Answer 1

1

First you will need to search the array to see if any duplicates exist. The following is one way to search an array.

const isDuplicate = (data, obj) =>
  data.some((el) =>
    Object.entries(obj).every(([key, value]) => value === el[key])
  );

The outer loop is searching for some element that matches every object property using the inner loop to the reference object value. If an element is found with all properties equal to the reference object, return true, false otherwise.

const data = [
  {
    time: "20:15",
    timezone: "IST"
  },
  {
    time: "01:30",
    timezone: "UST"
  }
];

const isDuplicate = (data, obj) =>
  data.some((el) =>
    Object.entries(obj).every(([key, value]) => value === el[key])
  );

console.log(
  isDuplicate(data, {
    time: "20:15",
    timezone: "IST"
  })
); // true
console.log(
  isDuplicate(data, {
    time: "21:15",
    timezone: "IST"
  })
); // false

Only update state if not a duplicate

if (!isDuplicate(state.frequency.time, selecttime)) {
  this.setState((state) => ({
    ...state,
    frequency: {
      ...state.frequency,
      time: [...state.frequency.time, selecttime],
    },
    )}
  ));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.