-1

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

I want to delete the string "cat" and "dog" but I want to print them only one time in the result. Can anyone help me?

dda
  • 6,030
  • 2
  • 25
  • 34
Sai
  • 17
  • 5

3 Answers3

0

There is no remove() method on the default Array object. You have to get the index of the elements, you want to remove and then use the 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);

If you want to make the array unique, you can do the following:

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);
dschu
  • 4,992
  • 5
  • 31
  • 48
0

Use the filter function.

var arr = ["cat", "dog", "bear", "cat", "bird", "dog", "dog","cat"];
arr = arr.filter(function(item, pos) {
    return arr.indexOf(item) == pos;
});
console.log(arr);
Sagar V
  • 12,158
  • 7
  • 41
  • 68
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));
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28