Aquí está mi matriz. ¿Cómo puedo eliminar duplicados en este tipo de estructura? Cuando mapeo sobre arr, obtengo los valores de cada matriz anidados en cada objeto. Y quiero filtrar los valores duplicados. salida actual: adiós hola hola La salida esperada debería ser: adiós hola
[ { 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> ))
Espero que te ayude:
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)
Y luego en JSX:
filteredArray.map(() => ...)
Todas estas respuestas son buenas... Creo que @vitaliyirtlach tiene la mejor ya que es la más cercana a React.
Solo diré que también puede recorrer myArray
, eliminar los duplicados con Set
y luego colocarlos en una matriz que puede recorrer:
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> ))
Simplemente puede administrar una matriz para filtrar lo que desea mostrar:
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'));
Aquí está la reproducción en StackBlitz .