Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
Contar y mostrar datos duplicados en JavaScript

Me gustaría contar y mostrar cuántos datos están cubiertos en cada matriz. Al principio, filtré y configuré solo la etiqueta que no está duplicada. Y luego conté cada uno como matriz. Pero no funcionaría...

 dataArray = ["a", "a", "bs", "bs", "bs", "bs", "vgvg"] const [count, setCounts] = useState<any[]>([]) const [labels, setLabels] = useState<any[]>([]) useEffect(() => { let b = dataArray.filter((x, i, self) => { return self.indexOf(x) === i }) setLabels(b) console.log(label) // ["a", "bs", "vgvg"] }, [dataArray]) useEffect(() => { let c = [] as any[] dataArray.map((data) => { c[data] = (c[data] || 0) + 1 }) setCounts(c) console.log(count) // {"a": 2, "bs": 4, "vgvg": 1} }, [dataArray]) return ( {labels.map((label, idx) => ( <div>{label}: {counts[label]}</div> ))} )

error

 Element implicitly has an 'any' type because index expression is not of type 'number'.
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Probablemente podría usar algo como Array.prototype.reduce para esto.

Tú podrías:

 const TestComponent = ({ dataArray }) => { // Memoise the counts so it doesn't need to be calculated on each render. const counts = useMemo(() => { // use array reduce to calculate counts. return dataArray.reduce( (state, item) => { // if property does not yet exist add it and set to 0 count. if (state[item] === undefined) { state[item] = 0; } // increment count state[item]++; // return updated state return state; }, {} //initial state ); }, [dataArray]); return ( { Object // Use Object.keys to get an array of property names .keys(counts) // Map property names to desired view (label / count) .map((key) => ( <div key={key} > {key}: counts[key] </div> )) } ) }

El ejemplo reduce la función dado un dataArray de:

 const dataArray = ["a", "a", "bs", "bs", "bs", "bs", "vgvg"]

Se reduciría a:

 const result = { a: 2, bs: 4, vgvg: 1 }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!