Home > Net >  comparing objects in useState and if there is object with same id keep one of them
comparing objects in useState and if there is object with same id keep one of them

Time:11-24

i'm react beginner, for some reason when i console log i get two japans any advices ?

these are my data:

options initial value (comes from props) is:

[{ id: 1, name: 'Japan' },{ id: 4, name: 'Australia' }, { id: 5, name: 'Poland' }];

and from redux i'm getting this:

[{ id: 1, name: 'Japan' }, { id: 2, name: 'America' }, { id: 3, name: 'Sweden' }];

but my expected out put is :

[{ id: 1, name: 'Japan' },{ id: 4, name: 'Australia' }, { id: 5, name: 'Poland' }, { id: 2, name: 'America' }, { id: 3, name: 'Sweden' }]

   const getUnselectedValues = useSelector(UnselectedValues);

 
 const [options, setOptions] = useState(
    props.selectedValues
      ? (
          [...props.selectedValues, ...getUnselectedValues] 
        ).filter((e ) => e)
      : [...getUnselectedValues]
  );
  
  console.log('options:', options)

CodePudding user response:

Try it:

const [options, setOptions] = useState(
    props.selectedValues
      ? Object.values([...props.selectedValues, ...getUnselectedValues].reduce((acc, {id, name}) =>(acc[id] ??= {id, name}, acc),{}))
      : [...getUnselectedValues]
  );

Approach:

  1. Iterate through the merged array and build a dictionary by using reduce() where the key is the id and the value is {id, value}
  2. In every iteration look up in the dictionary whether has the key in it or not. If the key is not present that means it's a unique entry and inserts it. If the key is already in the dictionary that means the entry is not unique so no need to insert it again.

Here is an example in Vanilla JS so you can play around:

const selectedValues = [{ id: 1, name: 'Japan' },{ id: 4, name: 'Australia' }, { id: 5, name: 'Poland' }];

const getUnselectedValues = [{ id: 1, name: 'Japan' }, { id: 2, name: 'America' }, { id: 3, name: 'Sweden' }];


const res = Object.values([...selectedValues, ...getUnselectedValues].reduce((acc, {id, name}) =>(acc[id] ??= {id, name}, acc),{}));

console.log(res);

Using filter():

const selectedValues = [{ id: 1, name: 'Japan' },{ id: 4, name: 'Australia' }, { id: 5, name: 'Poland' }];

const getUnselectedValues = [{ id: 1, name: 'Japan' }, { id: 2, name: 'America' }, { id: 3, name: 'Sweden' }];

const res = [...selectedValues, ...getUnselectedValues.filter(({id, name}) => !selectedValues.find(it => it.id === id))];

console.log(res);

  • Related