内容简介: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.
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
流畅的Python
[巴西] Luciano Ramalho / 安道、吴珂 / 人民邮电出版社 / 2017-5-15 / 139元
【技术大咖推荐】 “很荣幸担任这本优秀图书的技术审校。这本书能帮助很多中级Python程序员掌握这门语言,我也从中学到了相当多的知识!”——Alex Martelli,Python软件基金会成员 “对于想要扩充知识的中级和高级Python程序员来说,这本书是充满了实用编程技巧的宝藏。”——Daniel Greenfeld和Audrey Roy Greenfeld,Two Scoops ......一起来看看 《流畅的Python》 这本书的介绍吧!
图片转BASE64编码
在线图片转Base64编码工具
XML、JSON 在线转换
在线XML、JSON转换工具