[Interview question] How many ways do you think of to deduplicate arrays?

 Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

foreword

Have you been given an array to remove duplicates during the interview? At that time, in addition to using Set to implement in your mind, what deduplication method did you tell the interviewer? Can you encapsulate a reusable array deduplication API? I vaguely remember that when I was asked this question, I didn't answer many solutions. Then let me summarize the methods we can answer for the simple interview question of array deduplication.

Array deduplication

1. Do not use array API methods

First, let me introduce a deduplication solution that does not use the API on the array. The code is as follows:

var array = ['1', 1, '1', '1', '2', 2]
function unique(array) {
    let res = []
    for(let i = 0; i < array.length; i++){
        for( var j = 0; j < res.length; j++){
            if(array[i]  === res[j]){
                break;
            }
        }
        if(j === res.length){
            res.push(array[i])
        }
    }
    return res 
}
console.log(unique(array)); // [ '1', 1, '2', 2 ]

Since the API method that comes with the array is not used, the first thing we consider is to use double for loops, such as the above code:

  1. We prepare an empty result array
  2. We loop over the array that needs to be deduplicated
  3. Put another layer of loop in the first layer of data, and judge whether there are duplicates in the result array according to the subscript.

We call this method, print the structure as in the comment of the above code, and successfully realize the deduplication of the array.

2. Use indexOf

Since there are those who do not use the array API, there must be those who use the array API. Let’s see that I use indexOf to complete the deduplication of the array. The code is as follows:

var array = ['1', 1, '1', '1', '2', 2]
function unique(array) {
    let res = []
    for (let i = 0; i < array.length; i++) {
        if (res.indexOf(array[i]) === -1) { // 返回找到的第一个值得下标
            res.push(array[i])
        }
    }
    return res
}
console.log(unique(array))// [ '1', 1, '2', 2 ]

As in the above code, we cleverly used indexOf to find out whether the result array already exists, and if it does not exist, we add it to the result array, realizing the deduplication of the array.

On the basis of the above code, we can also change it and change the statement in the for loop to :

if (array.indexOf((array[i])) == array.lastIndexOf(array[i])) {
    i++
} else {
    array.splice(array.lastIndexOf(array[i]), 1)
}

No other variables are added, and the indexOf and lastIndexOf are used to directly judge whether the value is the only value in the original array, so as to directly modify the original array and realize deduplication of the array.

3. use sort

For array deduplication, in addition to finding out whether there are duplicates through subscripts, we can also sort them first, and then determine whether the preceding and following items are the same to achieve deduplication. The code is as follows:

var  array = [1, 3, 5, 4, 2, 1, 2, 4, 4, 4]
function unique(array) {
    let res = []
    let sortedArray = array.concat().sort() //concat() 返回新的数组
    let seen;
    for (let i = 0; i < sortedArray.length; i++) {
        if (!i || seen !== sortedArray[i]) {
            res.push(sortedArray[i])
        }
        seen = sortedArray[i]
    }
    return res
}
console.log(unique(array)); // [ 1, 2, 3, 4, 5 ]

As in the above code, we first obtain a new sorted array, and then loop through the new array to determine whether the seen that saved the previous value is the same as the current value to achieve deduplication of the array.

Reminder: Since the array sorting method cannot distinguish between arrays and strings, you must ensure that the values ​​​​of the arrays are of the same type if you want to use this method, otherwise there will be bugs

4. Use filter

Now that sorting is used, it is not too much for me to directly bring out the new filter API of ES6 arrays. The code is as follows:

var array = ['1', 1, '1', '1', '2', 2]
function unique(array) {
    let res = array.filter((item, index, array) => {
        return array.indexOf(item) === index
    })
    return res
}
console.log(unique(array)); // [ '1', 1, '2', 2 ]

As in the above code, the filter is directly used array.indexOf(item) === indexas the filter condition to return a new array to achieve deduplication of the array.

As in the above code, we combined the indexOf method as a filter condition, then we can also combine the sort method, and directly use one line of code to solve the deduplication of the array. code show as below:

function unique(array) {
    return array.concat().sort().filter((item, index, array) => !index || item !== array[item - 1])
}
console.log(unique(array)); // [ '1', 1, '2', 2 ]

5. Use Set, Map, or Object

In addition to the above-mentioned methods of using the array API and not using the array API, what we can think of is to use the object to realize the deduplication of the array. Using the Set data structure is the easiest way for us to think of. Using Map is similar to the object method, both of which use the value of the array as the key, and then take all the values ​​​​that can be taken out to form an array. I won't demonstrate the code to my friends, interested friends can try it by themselves.

(For the problem that the key of an object can only be a string, we can change the way of thinking, store the subscript as a key, and store the value as a value, and judge that the values ​​​​of different keys are different to realize the deduplication of the array. We can also save the key , plus its type, and then perform a conversion.)

Encapsulate a deduplication API by yourself

After introducing the above-mentioned methods for deduplication of arrays, let's summarize them and integrate them into an API method that is reusable and applicable to different situations.

Let me introduce the API method for deduplication of an array that I encapsulated as follows.

  1. This method accepts three parameters, the first parameter is the array that needs to be deduplicated, the second parameter is whether the array is a sorted array, and the third parameter is a callback function
  2. The callback function also has three parameters, which are the value, the subscript, and the array that needs to be deduplicated. The function of this callback function is to facilitate the user to perform some additional processing on the array (such as converting uppercase to lowercase)
  3. The second and third parameters may not be passed.
var array = [1, 2, '1', 'a', 'A', 2, 1]
var array2 = [1, 1, '1', 2, 2]
function uniq(array, isSorted, iteratee) {
    let  seen = []
    let res = []
    for(let i = 0; i < array.length; i++){
        let computed = iteratee ? iteratee(array[i], i,array) : array[i]
        if(isSorted) {
            if(!i || seen !== array[i]){
                res.push(array[i])
            }
            seen = array[i]
        }else if(iteratee) {
            if(seen.indexOf(computed) === -1){
                seen.push(computed)
                res.push(computed)
            }
        }
        else {
            if(res.indexOf(array[i]) === -1) {
                res.push(array[i])
            }
        }
    }
    return res
}
let result = uniq(array, false, function(item, index, arr){
    return typeof item == 'string' ? item.toLowerCase() : item
})
console.log(result); // [ 1, 2, '1', 'a' ]
console.log(uniq(array2, true)); // [ 1, 2 ]

Summarize

For the deduplication of arrays, when we can talk about this multi-method in the interview, this interview question will pass. Although this interview is not difficult, if we want to think of this multi-method, we still need a lot of knowledge Reserved.

 Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

 

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/131478557