Removing duplicates from an arrary with just one line of code

栏目: IT技术 · 发布时间: 5年前

内容简介:I was making a list of common interview questions for junior front-end developers. One common question that pops up quite often is how to remove duplicates from a JavaScript array.Let's say we have to the following array:To keep just the unique values we w

I was making a list of common interview questions for junior front-end developers. One common question that pops up quite often is how to remove duplicates from a JavaScript array.

Let's say we have to the following array:

const withDuplicates = ["dog", "cat", "dog", "cow", "dog", "cat"]

To keep just the unique values we will have:

const uniqueValues = [...new Set(withDuplicates)]
// it will return ["dog", "cat", "cow"]

Bam, that's all! Just one line!

It works as well with numeric values but does not work with objects .

The Set is a Javascript data structure and its main purpose is to be a container for data that can’t be repeated.

By initializing a Set with a destructured array (the ... operator before new Set()), we pass the actual values the Set will automatically remove the duplicates. Finally, we convert it back to an array by wrapping it into square brackets.

The Set was added in 2015 by the ES6 version of Javascript.

The old complex solution without using the ES6 Set

Before having Sets in Javascript we had to do this manually with a code similar to this one:

function remove_duplicates(arr) {
    var obj = {};
    var ret_arr = [];
    for (var i = 0; i < arr.length; i++) {
        obj[arr[i]] = true;
    }
    for (var key in obj) {
        ret_arr.push(key);
    }
    return ret_arr;
}

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

算法交易与套利交易

算法交易与套利交易

赵胜民 / 厦门大学出版社 / 2010-9 / 35.00元

《算法交易与套利交易》主要介绍算法交易和一些套利交易的策略,以便于读者对相关方面的内容进行阅读和学习。在《算法交易与套利交易》的第一部分,我们回顾了投资学一些相关的基本内容。其中,前两章介绍了证券投资的收益和风险等特征,以及马可维茨的最优资产配置模型。第3章则介绍了股票投资分析当中常用的资本资产定价模型(CAPM)、套利定价模型(APT),以及因素模型。然后,第4、5章分别讲到了金融证券估值模型、......一起来看看 《算法交易与套利交易》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码