Toggle values into and out of an array in Javascript

前端 未结 4 962
臣服心动
臣服心动 2021-02-19 05:08

I want to have a simple array of values, ie

var simpleArray = [\"SE1\",\"SE2\",\"SE3\"];

I want to check this array when an action happens (a c

4条回答
  •  礼貌的吻别
    2021-02-19 05:31

    Also if the value is an object:

    const eq = (a, b) => a == b
    
    const toggle = (arr, item) => {
      const resultArray = [];
      let duplicate = false;
      for(let i = 0; i < arr.length; i++) {
        if(!eq(arr[i], item)) {
          resultArray.push(arr[i]);
        } else {
          duplicate = true
        }
      }
      if(!duplicate) {
        resultArray.push(item)
      }
      return resultArray;
    }
    

提交回复
热议问题