Home > Software design >  Remove duplicates from inner array of array of objects
Remove duplicates from inner array of array of objects

Time:03-11

Here is my array. How can I remove duplicates in this type of structure? When I map over arr I get the values of each array nested in each object. And I want to filter the duplicated values. current output: bye hello hello The expected output should be: bye hello

[

    {
        arr: ['']
        val: "string"
    }
    {
        arr: ['bye', 'hello']
        val: "string"
    }
    {
        arr: ['hello']
        val: "string"
    }

]
    
    
myArray.map(item => item.arr.map((el, index) =>
    <p key={index}>{el}</p>       
))

CodePudding user response:

I hope it will help you:

const filteredArray = useMemo(() => {
   const used = []
   
   return myArray.map(sub => {
      return { ...sub, arr:sub.arr.map(el 
    => {
      if(used.includes(el) return null
      used.push(el)
      return el
    }}
   })
}, deps)

And then in JSX:

filteredArray.map(() => ...)

CodePudding user response:

You could simply manage an array to filter what you want to display :

import React from 'react';
import { render } from 'react-dom';
import './style.css';

const App = () => {
  const data = [
    {
      arr: [''],
      val: 'string',
    },
    {
      arr: ['bye', 'hello'],
      val: 'string',
    },
    {
      arr: ['hello'],
      val: 'string',
    },
  ];

  const buildData = () => {
    const passedValues = [];
    return data.map((item) => {
      return item.arr.map((el) => {
        if (!passedValues.includes(el)) {
          passedValues.push(el);
          return <div>{el}</div>;
        }
      });
    });
  };

  return <div>{buildData()}</div>;
};

render(<App />, document.getElementById('root'));

Here is the repro on StackBlitz.

CodePudding user response:

All of these answer are good...I think @vitaliyirtlach has the best as its the closest to React.

I'll just put it out there that you can also loop through myArray, remove the duplicates with Set and then place them in an array that you can loop over:

    const myArray = [
    
        {
            arr: [''],
            val: "string"
        },
        {
            arr: ['bye', 'hello'],
            val: "string"
        },
        {
            arr: ['hello'],
            val: "string"
        }
    
    ]
    
    const removeDupes = () => {
      const newArr = []
      myArray.map(item => item.arr.map((el, index) =>
        newArr.push(el)     
      ))
      return [...new Set(newArr)]
    }
    
    const loopArray = removeDupes();
    
    console.log(loopArray)// logs ["","bye","hello"]

    loopArray.map((el, index) =>
      <p key={index}>{el}</p>
    ))    
  • Related