Do front-end development years, in the project to use the array to redo the opportunity is not a lot, but in the interview was often asked, personal understanding, this question is really test of the basic mastery of JavaScript, because there are many ways to do it. This time on the basis of this problem, the relevant knowledge to understand thoroughly.

New Set in ES6

Let’s look at the description of Set in MDN.

The Set object allows you to store a unique value of any type, either a primitive value or an object reference.

A Set object is a collection of values, and you can iterate over its elements in the order in which they were inserted. Elements in a Set occur only once, that is, the elements in a Set are unique.

Keyword: any type can be stored, stored in the value is unique, so that you can do first in the array of duplicate data to remove.

const list1 = [1, 2, 3, 7, 11, 56, 3, 2, 4, 5]
const list2 = new Set(list1)
console.log(list2) 
Copy the code

Take a look at the result returned:

The result shows that an iterable Set object is returned, and the Set object needs to be converted into an array. You can use

Array. The from ().

The ** array.from ()** method creates a new, shallow-copy Array instance from an array-like or iterable.

Just so happens that new Set() returns an iterable object.

const list3 = Array.from(new Set([null, null, undefined, 12, undefined, 7, 2, 1, 22, 2, function a(){}, function a(){}, {}, {}))Copy the code

The result is an array returned:

This approach does not consider compatibility and does not eliminate duplicate functions and {}.

Extensions to array.from ()

Array.from(arrayLike[, mapFn[, thisArg]])

ArrayLike: pseudo-arrays and iterables

MapFn: Each element executes this callback method

ThisArg: this refers to when the callback is executed.

const list4 = Array.from('name', arg => arg + 12)
console.log(list4) // [ 'n12', 'a12', 'm12', 'e12' ]
Copy the code
  • The pseudo-array object (has onelengthProperty and several index properties, such as string)
  • Iterable (you can get elements of an object, such as maps and sets)

2. another way of writing set

const list20 = [5, 3, 5, 5, 6, 37, 22, 22]
console.log([...new Set(list20)])
Copy the code

It’s actually similar to the first one

Nested for loops

const list5 = [null, null, undefined, undefined, {}, {}, function q() {}, function q() {}, 34, 2, 1, 2] for(let i = 0; i < list3.length; i++) { for (let j = i + 1; j < list3.length; If (list3[I] === list3[j]) {list3.splice(j, 1) {list3.splice(j, 1)}}Copy the code

This method uses the splice(index, num) method and returns the same result as function and object. The simplest way we can think of is this de-weighting method.

4. IndexOf

const list6 = [null, null, undefined, undefined, NaN, NaN, false, 'false', function a(){}, function a() {}, {}, {}]
const list7 = []
for(let k = 0; k<list6.length; k++) {
    if (list7.indexOf(list6[k]) === -1) {
        list7.push(list6[k])
    }
}
console.log(list7, 'list7') 
// [null, undefined,NaN, NaN,false,'false',[Function: a], [Function: a],{},{}] list7
Copy the code

About the indexOf

Both the Array constructor and the String constructor prototype have this method

MDN explains them as follows:

The **indexOf()** method returns the first index where a given element can be found in the array, or -1 if none exists.

arr.indexOf(searchElement[, fromIndex])
Copy the code

The **indexOf()** method returns the indexOf the first occurrence of the specified value in the String calling it, searched from fromIndex. If the value is not found, -1 is returned.

str.indexOf(searchValue [, fromIndex])
Copy the code

You can tell they use it the same way.

Five, the sort

First look at the explanation of sort:

The **sort()** method sorts the elements of an array using an in-place algorithm and returns the array. The default sort order is built when converting elements to strings and then comparing their UTF-16 code unit value sequences

Because it is implementation-dependent, the temporal and spatial complexity of sorting cannot be guaranteed.

So this way, you may not be able to guarantee performance when the array is long. What is the idea of using it to get rid of weight? Sort first and then compare the previous one to the next so that the same value is always a neighbor.

const list8 = [null, null, undefined, undefined, NaN, NaN, false, 'false', function a(){}, function a() {}, {}, {}] const list9 = list8.sort() const list10 = [list9[0]] for(let i = 1; i<list9.length; i++) { if (list9[i] ! == list9[i-1]) { list10.push(list9[i]) } }Copy the code

This is easy to understand at first sight.

Six, includes

const list11 = [null, null, undefined, undefined, NaN, NaN, false, 'false', function a(){}, function a() {}, {}, {}] const list12 = [] for (let i = 0; i<list11.length ; i++) { if (! list12.includes(list11[i])) { list12.push(list11[i]) } }Copy the code

This result does not duplicate function and {}, but all others.

Includes is also a method on both the Array constructor and String constructor.

Filter and indexOf

// Filter 6-filter and indexOf const list13 = [1, 2, 3, 3, 5] const list14 = list13. Filter ((item, index, Arr) => {// compare the current element to the first occurrence of the element in the list13 array. Return list13.indexof (item, 0) === index})Copy the code

Eight, the recursion

const list15 = [1, 2, 3, 4, 5, 7, 6, 4, 3] const list16 = list15 const len = list16.length list16.sort(function(a, Function loop(index) {if (index >= 1) {if (list16[index] === list16[index - 1]) {if (list16[index] === list16[index - 1]) { list16.splice(index, 1) } loop(index - 1) } } loop(len - 1)Copy the code

About Sort

We may have overlooked a problem when sorting, and may not get the result we want, as in the following example:

const list17 = [22, 1, 2, 15, 3, 4, 3, 1, 11]
console.log(list17.sort()) // [1, 1, 11, 15, 2, 22, 3,  3,  4]
Copy the code

And if you look at the results, they’re not in order at all. This is because the default sort order is built when elements are converted to strings and then their UTF-16 code unit value sequences are compared.

So to find another way to sort, pass a function to sort.

arr.sort([compareFunction])

Parameters:

  • CompareFunction: Passable or not, which is used to specify functions in a certain order. If omitted, the element is sorted by the Unicode loci of each character in the converted string.

  • Parameter 1-FIRstel to compareFunction: the first element used for comparison

  • Parameter to compareFunction 2-secondel: the second element used for comparison

  • If compareFunction(a, b) is less than 0, then A is placed before B;

  • If compareFunction(a, b) is equal to 0, the relative positions of a and B remain the same. Note: The ECMAScript standard does not guarantee this behavior, and not all browsers comply (Mozilla prior to 2003, for example);

  • If compareFunction(a, b) is greater than 0, b will be placed before A.

  • CompareFunction (a, b) must always return the same comparison result on the same input, otherwise the sorting result will be indeterminate.

The return value:

Returns an array that has been sorted in place.

9. Sort by Map data structure

const list 18 = [2, 3, 33, 2, 5, 1, 3]
const map1 = new Map()
for(let i = 0; i<list18.length; i++) {
    if (map1.get(list18[i])) {
        map1.set(list18[i], true)
    } else {
        map1.set(list18[i], false)
        list19.push(list18[i])
    }
}
Copy the code

This is easier to understand, so I won’t go into it.