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.


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

查看所有标签

猜你喜欢:

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

Web信息架构(第3版)

Web信息架构(第3版)

Peter Morville、Louis Rosenfeld / 陈建勋 / 电子工业出版社 / 2008年8月 / 85.00

本书涵盖了信息架构基本原理和实践应用的方方面面。全书共7个部分,包括信息架构概述、信息架构的基本原理、信息架构的开发流程和方法论、信息架构实践、信息架构与组织、两个案例研究,以及参考资料清单。 本书兼具较高的理论价值和实用价值,曾被Web设计领域多本书籍重点推荐,是信息架构领域公认的经典书,不论新手还是专家都能各取所需。本书可供Web设计与开发者、Web架构师、网站管理者及信息管理相关人员参......一起来看看 《Web信息架构(第3版)》 这本书的介绍吧!

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

RGB HEX 互转工具

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

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具