0

I am currently receiving object segregatedData as props. This object contains several properties but the one we will focus on is segregatedData.type1 Basically this is just an array of strings like this ['water','fire','water',earth'] What I'd like to is to be able to print out each string and then beside it is how many instances this value has been repeated. So in the example case the expected output would be water-2, fire-1, earth-1 Of course we'd have to delete the duplicates.

Here's what I have so far:

import React from "react";
import { Typography } from "@material-ui/core";

function TypesText(props) {
  const { segregatedData } = props;
  return (
    <>
      <Typography>Type1:</Typography>
      {segregatedData.length && segregatedData.map((data) => data.type1 + " ")}
    </>
  );
}

export default TypesText;

Fairly basic, it just prints every type1 property with a blank string as its seperator. Anything that can point me in the right direction is appreciated.

Pacholoamit
  • 245
  • 6
  • 16
  • 1
    You want to get the frequency/count of each element in your array: [Counting the occurrences / frequency of array elements](https://stackoverflow.com/a/57028486) – Nick Parsons Dec 05 '20 at 11:14

1 Answers1

0

use segregatedData.type1.reduce to output array that finds occurrence in output array via mapping it and using string.search to find occurrence and then incrementing integer at the end.

Take a look at following code sample. test it

const arr = ['water','fire','water', 'earth'];
let val = arr.reduce((resultarr, item) => { 
   const val = resultarr.find(item1 => item1.search(item) !== -1) 
   const ind = resultarr.findIndex(item1 => item1.search(item) !== -1) 

   if (val == undefined) {
      resultarr.push(item + "-" + 1)
   }
   else {
      const i = val.search("-")
      const num = parseInt(val.substring(i+1))
      const nval = item + "-" + (num+1)
      resultarr[ind] = nval;
   }
   return resultarr
}, [])
alert(val);
Ayaz Alavi
  • 4,825
  • 8
  • 50
  • 68