Domenico Giacomo Campanile

Sviluppatore e Consulente Informatico

REACT: Add item into array if it does not exist otherwise delete it

Add item into array if it does not exist otherwise delete it

import React from 'react';

class PushOrSpliceArray extends React.Component {

state = {array: []}

  addItemArray = (item) => {

    var newArray = [...this.state.array]
    var indexItem = newArray.indexOf(item)
    indexItem === -1 ? newArray.push(item) : newArray.splice(item, 1);
    this.setState({ array: newArray });

  }
}