0

I'm creating an app where when a button is clicked, the value of that item is added to the state. The button can be clicked multiple times, so the state array can hold the same item multiple times.

As of right now I have:

export defaul class Parent extends Component{
  this.state = {array: []}

  onAdd = item => {
    this.setState({array: [...this.state.array, item]});
  }
  render() {
    return(
      ...
      <button onClick{() => {onAdd()}} > Add </button>
      ...
    );
  }
}

How would I get the number of times a specific item exists in that array?

EDIT: There are many different items, with various lengths of names, so having a line to check each doesn't seem best practice.

The items look like this:

export const item = [
  {
    id: some int id
    name: some String name
    type: some category as a String
    available: boolean
  }
]
  • Maybe with [filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter): `array.filter(x => x === ).length` – Shidersz Feb 14 '19 at 15:13
  • check this one: https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements][1] – Cespejo Feb 14 '19 at 15:13

1 Answers1

0

You can use reduce to transform your array into a count without returning an array like filter does

function numItems (array, item) {
  return array.reduce((count, curr) => {
    return curr === item
      ? sum + 1
      : sum;
  }, 0);
}
Saraband
  • 1,540
  • 10
  • 18