Removing duplicates from an arrary with just one line of code

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

内容简介: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.


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

查看所有标签

猜你喜欢:

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

逆袭大学

逆袭大学

贺利坚 / 人民邮电出版社 / 2014-3 / 49.00

《逆袭大学——传给IT学子的正能量》以作者近二十年的从教经历和义务为IT学子解答咨询的工作为基础,以认识专业为起点,以编程能力的提高为关键,帮助计算机类专业的大学生更新学习观念、重塑学习品质、培养学习方法,找到自己的大学之路。书中直接解答了学无用处论、专业兴趣、考研、职场等诸多大学生面临的典型困惑。 本书主要面向在校计算机类(包括软件工程、网络工程等)专业高校学生,也能让非计算机类专业的高校......一起来看看 《逆袭大学》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换