在 JavaScript 中删除数组中多次出现的元素的所有实例

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/8 1:48:17

我们需要编写一个 JavaScript 函数,该函数接受一个文字值数组。

该数组可能包含一些重复值。

我们的函数应该从数组中删除所有重复的值。我们需要删除所有此类元素的所有实例。

示例

其代码为 −

const arr = [1, 2, 3, 2, 4];
const removeAllInstances = (arr = []) => {
   filtered = arr.filter(val => {
      const lastIndex = arr.lastIndexOf(val);
      const firstIndex = arr.indexOf(val);
      return lastIndex === firstIndex;
   });
   return filtered;
};
console.log(removeAllInstances(arr));

输出

控制台中的输出将是 −

[ 1, 3, 4 ]

相关文章


有用资源