在 javascript 中从数组中删除重复的内容-ag捕鱼王app官网

在 javascript 中从数组中删除重复的内容

作者:迹忆客 最近更新:2023/05/09 浏览次数:

本教程将解释我们如何在 javascript 中使用不同的方法从数组中删除重复的数组。其中一种方法是将目标数组传递给 set 类的构造函数,以返回一个等价的非重复数组。另一种方法是使用 javascript array 的 filter() 方法,并在其回调函数中实现测试条件。

在数学中,集合包含一组唯一的、非重复的元素。在 javascript 中,set 类可以从一个数组中得到所有这些非重复的元素。

ecmascript 6 中,我们可以通过使用 set 类来获得一个新的非重复元素数组,并将其发送给 set() 构造函数,从而使用传播语法的力量。

var arr = [1,2,3,4,1,2,3,1,2,3]
var uniquearr = [...new set(arr)]
console.log(uniquearr)

输出:

[1, 2, 3, 4]

javascript 数组引入了一个名为 filter() 的高阶函数,它对每个数组元素进行循环,对其应用一个测试条件,只有在满足条件时才返回该元素。这个测试条件将在回调函数里面实现,作为参数传递给 filter() 方法。

我们可以通过设置测试条件来检查当前元素在循环中的索引是否是该数组中的第一次出现,从而从数组中删除重复的元素。filter() 函数在执行过程中,会取额外的参数 pos 来代表元素的数组索引。

var arrtwo=["hello 1 "," hello 2 ","hello 1 " , " hello 2 ","hello 1 again"]
const filteredarray = arrtwo.filter(function(ele , pos){
    return arrtwo.indexof(ele) == pos;
}) 
console.log("the filtered array ",filteredarray);

输出:

the filtered array  (3) ["hello 1 ", " hello 2 ", "hello 1 again"]

如果我们能使用 javascript ecmascript 6 的箭头语法,那么删除重复操作就能更好地实现。

var arrtwo=["hello 1 "," hello 2 ","hello 1 " , " hello 2 ","hello 1 again"];
const filteredarray = arrtwo.filter( (ele,pos)=>arrtwo.indexof(ele) == pos);
console.log("the filtered array",filteredarray);

输出:

the filtered array  (3) ["hello 1 ", " hello 2 ", "hello 1 again"]

如果我们有一个数组只由数字 [ 1, 2, 3, 4, 1, 2, 3 ] 这样的基元类型组成,而我们想从这个数组 [ 1, 2, 3, 4 ] 中删除重复的值,我们可以使用 hashtables 实现我们的 filterarray() 函数。

我们将建立一个名为 found 的临时对象,它将包含所有非重复的值。在 filter 函数中,如果元素已经存在于 found 对象中,我们的条件将返回 false;否则,我们将以 true 的值将该元素添加到 found 对象中。

var arrthree = ["hello 1 ", " hello 2 ", " hello 2 ", "welcome", "hello 1 again", "welcome", "goodbye"]
function filterarray(inputarr){
    var found ={};
    var out = inputarr.filter(function(element){
        return found.hasownproperty(element)? false : (found[element]=true);
    });
    return out;
}
const outputarray = filterarray(arrthree);
console.log("original array",arrthree);
console.log("filtered array",outputarray);

输出:

original array ["hello 1 ", " hello 2 ", " hello 2 ", "welcome", "hello 1 again", "welcome", "goodbye"]
filtered array ["hello 1 ", " hello 2 ", "welcome", "hello 1 again", "goodbye"]

如果我们已经在使用 underscore 库中的任何一种方法,我们可以使用 _.uniq() 方法,因为它只返回输入数组中元素的第一次出现。

var arrfive = [1, 2, 3, 1, 5, 2];
console.log("lodash output", _.uniq(arrfive));

上一篇:

下一篇:

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

如何从 pandas 的日期时间列中提取月份和年份

发布时间:2024/04/23 浏览次数:160 分类:python

我们可以分别使用 dt.year()和 dt.month()方法从 datetime 列中提取出年和蛾。我们还可以使用 pandas.datetimeindex.month 以及 pandas.datetimeindex.year 和 strftime()方法提取年份和月份。

如何获取 pandas dataframe 的行数

发布时间:2024/04/23 浏览次数:71 分类:python

本教程介绍如何通过使用 shape,len()来获取 pandas dataframe 的行数,以及有多少行元素满足条件。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图