在javascript中从数组中删除元素?

时间:2017-03-28 09:48:59

标签: javascript jquery

var arr = ["cat", "dog", "bear", "cat", "bird", "dog", "dog","cat"];
arr.remove("cat", "dog");
console.log(arr);

我想删除字符串“cat”和“dog”但我想在结果中只打印一次。任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

默认remove()上没有Array object方法。 您必须获取要删除的元素的索引,然后使用splice() method

const arr = ["cat", "dog", "bear", "cat", "bird", "dog", "dog","cat"];
const toRemove = ["cat", "dog"];

console.log('before', arr);

toRemove.forEach(item => {
  const itemPosition = arr.indexOf(item);
  arr.splice(itemPosition, 1);
});

console.log('after', arr);

如果要使数组唯一,可以执行以下操作:

const arr = ["cat", "dog", "bear", "cat", "bird", "dog", "dog","cat"];

uniqueArray = arr.filter(function(item, pos, self) {
    return self.indexOf(item) == pos;
})

console.log(uniqueArray);

答案 1 :(得分:0)

使用过滤功能。



var arr = ["cat", "dog", "bear", "cat", "bird", "dog", "dog","cat"];
arr = arr.filter(function(item, pos) {
    return arr.indexOf(item) == pos;
});
console.log(arr);




答案 2 :(得分:0)



/**
 * Takes an array of primitive values and returns a list with unique values
 *
 * @param {(string[] | number[] | boolean[])} arr
 * @param {boolean} [preserve=false]
 * @returns
 */
function uniqueArray(arr, preserve) {
  if (preserve === void 0) {
    preserve = true;
  }
  //Handle preservation of original array
  var newArr;
  if (preserve === true) {
    newArr = arr.slice(0);
  } else {
    newArr = arr;
  }
  //Loop through array, from lowest to highest index
  for (var a = 0; a < newArr.length; a++) {
    //Loop through remainder of array based on index a
    for (var b = a + 1; b < newArr.length; b++) {
      //If values are the same
      if (newArr[a] === newArr[b]) {
        //Remove this index in the array
        newArr.splice(b, 1);
        //Offset b index to handle the rearranged array
        b--;
      }
    }
  }
  //Return unique array
  return newArr;
}
//TEST
var arr = ["cat", "dog", "bear", "cat", "bird", "dog", "dog", "cat"];
console.log(uniqueArray(arr));
&#13;
&#13;
&#13;