内容简介: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.
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
生态战略:设计未来企业新模式
周文艺 / 机械工业出版社 / 2017-3 / 49.00
思想影响战略,战略决定组织。在充满高度不确定性的今天,企业要生存和发展,必须不断进行组织变革与进化,跨越不连续性的鸿沟。本书分析了大量互联网生态型企业的案例,从生态思维进化、生态战略构建和生态组织变革三个角度出发,全面阐述了企业的进化之路。 本书认为,生态是企业进化的核心思想,企业须重新定义增长模式,从封闭的企业链转向开放的价值网,不断创新文化、技术和连接,培育新物种,实现企业从技术生态位到......一起来看看 《生态战略:设计未来企业新模式》 这本书的介绍吧!