Home >Web Front-end >JS Tutorial >JavaScript Topic 2: Array Deduplication
Directory
Write at the end
(Related free learning recommendations: javascript video tutorial)
1. Double-layer circulation
const unique = (arr)=>{ for(let i = 0; i { var arr = [1, '1', '1', 1, 2, true, false, true, 3, 2, 2, 1]; var newArr = []; for(let i = 0; i <p><strong>Core point:</strong></p>
O(n^2)
2. indexOf and includes
Core point:
indexOf
method (not equal to the position where it first appeared ) when using splice
to remove indexOf
: Returns the first index
where a given element can be found in the array, if not If exists, -1 is returned. indexOf(ele, fromIndex)
##Code:
const unique = (arr) => { var res = []; for (let i = 0; i 2.2 includesSimplify one layer of loop judgment<h5></h5><p>Core point:<strong></strong></p>
: Used Determine whether an array contains a specified value. Depending on the situation, if it does, it will return
true, otherwise it will return
false
ele: The element to be found
Return result (bool)const unique = (arr) => {
var res = [];
for (let i = 0; i
2.3 indexOf and includes selection for the current scene
if(res.indexOf(arr[i]) !== -1 ){ todo }// orif(res.includes(arr[i])){ todo }
NaNIf there is
in the array, and you just need to determine whether the array exists NaN
, then you use indexOf
cannot be judged, you must use the includes
method. <pre class="brush:php;toolbar:false">var arr = [NaN, NaN];arr.indexOf(NaN); // -1arr.includes(NaN); // true</pre>
undefinedIf there is an
value in the array, includes
will think The empty value is undefined
, but indexOf will not. <pre class="brush:php;toolbar:false">var arr = new Array(3);console.log(arr.indexOf(undefined)); //-1console.log(arr.includes(undefined)) //true</pre>
Core point:
After the array is sorted, the same elements will Adjacent, so if the current element is different from its adjacent elements, it is stored in a new array;
var arr = [1, 1, '1'];function unique(arr) {
var res = [];
var sortedArr = arr.concat().sort();
var last;
for (var i = 0; i
Core point:
filter: method creates a new array containing all elements of the test
callback accepts three parameters: element-the element currently being processed, index-the current element index, array-the filter was called The array itselfvar arr = [1, 2, 1, 1, '1'];const unique = function (arr) {
var res = arr.filter(function(item, index, arr){
return arr.indexOf(item) === index;
})
return res;}console.log(unique(arr)); // [ 1, 2, '1' ]
Combined sorting ideas :
var arr = [1, 2, 1, 1, '1'];const unique = function (arr) { return arr.concat().sort().filter(function(item, index, arr){ return !index || item !== arr[index - 1] })}console.log(unique(arr));5. Key-value pair
The methods mentioned above can be roughly divided into
Non-sorted array, two traversal judgments (traversal, query)Take
[1,1,1,2,2,3,'3']for example: <ol>
<li>统计每个元素出现的次数,obj:{1: 3, 2: 2, 3: 3}, 返回这个<code>obj
的key
而不管他们的value
var arr = [1, 2, 1, 1, '1', 3, 3];const unique = function(arr) { var obj = {}; var res = []; arr.forEach(item => { if (!obj[item]) { obj[item] = true; res.push(item); } }); return res;}console.log(unique(arr)); // [1, 2, 3]
var arr = [1, 2, 1, 1, '1'];const unique = function(arr) { var obj = {}; return arr.filter(function(item, index, arr){ return obj.hasOwnProperty(item) ? false : (obj[item] = true) })}console.log(unique(arr)); // [1, 2]
对象的属性是字符串类型的,即本身数字1
和字符串‘1’
是不同的,但保存到对象中时会发生隐式类型转换,导致去重存在一定的隐患。
考虑到string和number的区别(typeof 1 === ‘number’, typeof ‘1’ === ‘string’),
所以我们可以使用 typeof item + item
拼成字符串作为 key 值来避免这个问题:
var arr = [1, 2, 1, 1, '1', 3, 3, '2'];const unique = function(arr) { var obj = {}; var res = []; arr.forEach(item => { if (!obj[typeof item + item]) { obj[typeof item + item] = true; res.push(item); } }); return res;}console.log(unique(arr)); // [ 1, 2, '1', 3, '2' ]
六、ES6
随着 ES6 的到来,去重的方法又有了进展,比如我们可以使用 Set 和 Map 数据结构。
Set:它允许你存储任何类型的唯一值,无论是原始值或者是对象引用
代码:
var arr = [1, 2, 1, '1', '2'];const unique = function(arr) { return Array.from(new Set(arr));}console.log(unique(arr)); // [ 1, 2, '1', '2' ]
简化1:
function unique(array) { return [...new Set(array)];}
简化2:
var unique = (a) => [...new Set(a)]
Map 对象保存键值对,并且能够记住键的原始插入顺序。任何值(对象或者原始值) 都可以作为一个键或一个值。
function unique (arr) { const newMap = new Map() return arr.filter((a) => !newMap.has(a) && newMap.set(a, 1));}
写到这里比较常规的数组去重方法就总结的差不多了,如果需要更强大的去重方法,我们需要对他们进行组合,而且因为场景的不同,我们所实现的方法并不一定能涵盖到
相关免费学习推荐:javascript(视频)
The above is the detailed content of JavaScript Topic 2: Array Deduplication. For more information, please follow other related articles on the PHP Chinese website!