1. How to solve an array deduplication problem
I read a lot of interview related questions, found that the array to redo several times, here on the array to redo the problem for a summary. And expand. Be sure to see chapter 2!
Problem description: Array deduplication, as the name implies, is to remove the duplicate values in the array, so that multiple identical values into one, and finally make the array does not contain duplicate values.
For example: one array:,2,3,4,4,5,5,5,6,7 [1], the array to heavy becomes,2,3,4,5,6,7 [1].
There are many solutions to this problem, which will be listed one by one here, and the individual important points will be extended
Solution will be from shallow to deep 😏, be sure to see the last few solutions!
🤔 Solution 1:
Use double for and splice
// double for and splice
function unique(arr){
for(var i=0; i<arr.length; i++){
for(var j=i+1; j<arr.length; j++){
if(arr[i]==arr[j]){
// The first is the same as the second, and the splice method deletes the second
arr.splice(j,1); j--; }}}return arr;
}
Copy the code
2 🤔 method
Use indexof method and new array
/ / use indexof
function unique(arr) {
var array = [];// Use a new array
for (let i = 0; i < arr.length; i++) {
if (array.indexOf(arr[i]) === -1) {
// Indexof returns -1 to indicate that the element does not exist in the new array
array.push(arr[i])// Push an element that is not in the new array}}return array;
}
Copy the code
You can also determine whether a value is included using includes
function unique(arr) {
var array =[];
for(var i = 0; i < arr.length; i++) {
if( !array.includes(arr[i]) ) {
//includes checks whether the array has a valuearray.push(arr[i]); }}return array
}
Copy the code
-
The indexOf() method returns the first index in the array where a given element can be found, or -1 if none exists. There are two arguments, the first is the element to look for and the second, optional, is the location to start the search. If the index value is greater than or equal to the length of the array, it means that it is not searched in the array, and returns -1. If the index value provided in the argument is a negative value, it is treated as an offset at the end of the array, where -1 means starting from the last element and -2 means starting from the penultimate element, still looking through the array from front to back. If the offset index is still less than 0, the entire array will be queried. The default value is 0
-
The includes() method is used to determine whether an array contains a specified value, returning true if it does and false otherwise. It also takes two arguments: the first is the element to search for, and the second, optional, is the starting point of the search. The default is 0
🤔 solution 3
Sort first using the sort method so that all the same elements are adjacent
function unique(arr) {
arr = arr.sort((a, b) = > a - b)//sort from smallest to largest
var arrry= [arr[0]].for (var i = 1; i < arr.length; i++) {
if(arr[i] ! == arr[i-1]) { arrry.push(arr[i]); }}return arrry;
}
Copy the code
The sort method is used to sort from smallest to largest (returning a new array), and without the above callbacks in its arguments the sorting error occurs at two digits or more (if omitted, the elements are sorted by the Unicode point of each character in the converted string). The two-digit number is converted to a string of length two for calculation. So you have to write a sort criterion that reverses the order of the two values when the callback returns a value greater than zero.
4 🤔 method
ES6 provides a new data structure, Set. Set can be de-weighted very easily
function unique(arr) {
const result=new Set(arr);
return [...result];
// Use the extension operator to convert a Set data structure into an array
}
Copy the code
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.
5 🤔 method
Using the Map
function unique(arr) {
let map = new Map(a);let array = new Array(a);// The array is used to return the result
for (let i = 0; i < arr.length; i++) {
if(map.has(arr[i])) { // If there is a key value
map.set(arr[i], true);
} else {
map.set(arr[i], false); // If there is no key valuearray.push(arr[i]); }}return array ;
}
Copy the code
The Map object holds key-value pairs and can remember the original insertion order of the keys. Any value (object or raw value) can be a key or a value.
Map.prototype.has(key)
Returns a Boolean value indicating whether the Map instance contains the value corresponding to the key.Map.prototype.set(key, value)
Sets the value of the key in the Map object. Returns the Map object.
6 🤔 method
Use the filter
function unique(arr) {
return arr.filter(function (item, index, arr) {
// Current element, the first index in the original array == current index value, otherwise return current element
// If it is not a duplicate item, discard it
returnarr.indexOf(item) === index; })}Copy the code
The filter() method creates a new array containing all the elements of the test implemented by the provided function. Its callback takes three arguments (the current element in the array being processed, the index of the element being processed in the array (optional), and the array itself being called (optional).
7 🤔 method
Use reduce plus includes
function unique(arr){
let result=arr.reduce((acc,cur) = >{
if(! acc.includes(cur)){ acc.push(cur); }returnacc; }, [])//[] as the initial value of the first argument to the callback function
return result
}
Copy the code
2. Array de-resolve method 7 leads to another interview question about reduce
Reduce has many uses and is very important. Here we fill up the knowledge point explanation of reducer.
Introduce the reduce
It is described in MDN as follows: The reduce() method performs a reducer function (ascending execution) provided by you on each element in the array, summarizing its results into a single return value. It can do a lot of functions, through the callback function.
The first argument to reduce is a callback function that takes four arguments (accumulator, current value, current index, and original array), the latter two optional. The second argument is the initial value of the accumulator for the first argument of the callback function (important)
Note: if no initial value is given, then the initial value is the first element of the original array, and the calculation starts with the second element. Given an initial value, you start with the first element.
See how reduce and its callback function are written using code implementation features:
- Sums the values of stored values
let result=[1.2.3.4].reduce((acc,cur) = >{
return acc+cur;//acc is the accumulator (the initial value is the first element of the array) and cur is the current element
})
console.log(result);/ / output 10
// There is no initial value, so we start from the second element of the array
Copy the code
- The sum is given to the initial value
Let the result = [1, 2, 3, 4] reduce (acc, cur, index, o = > {return acc + cur; },10) console.log(result); // The first element of the array is evaluated because there is an initial value, so the above array is processed. The callback is run 4 timesCopy the code
- Classify objects by their properties
const bills=[{type:'transfer'.momey:233},
{type:'study'.momey:341},
{type:'shop'.momey:821},
{type:'transfer'.money:821},
{type:'study'.momey:821}]let result=bills.reduce((acc,cur) = >{
if(! acc[cur.type]){// If a type does not exist, create an empty array
acc[cur.type]=[];// A two-dimensional array
}
acc[cur.type].push(cur)
returnacc; }, [])// Set the initial value of the accumulator to an empty array as a container for sorting
console.log(result);
/ / output
[
transfer: [{ type: 'transfer'.momey: 233}, {type: 'transfer'.money: 821}].study: [{type: 'study'.momey: 341 }, { type: 'study'.momey: 821}].shop: [{type: 'shop'.momey: 821}]]Copy the code
Reduce interview questions
🤔 Use native JavaScript to implement a method that determines which tags occur most frequently in HTML and counts the number of tags.
Knowledge details:
-
Get all tags:
Document.queryselector (*): Lists all the tags in the page, * represents the selector *, which is all.
-
Object.entries()
:Object.entries() returns an array of elements corresponding to key and value pairs of enumerable properties found directly on Object. The order of properties is the same as that given by manually looping through the object’s property values. In simple terms, you can turn each property of an object into an array with two values, one for the property name and one for the property value. For example: Object. Entires ({2, a: 1, b: c: 3}) will get [[‘ a ‘, 1], [‘ b ‘, 2], [‘ c ‘, 3]]
1. Obtain the NodeList array containing all tags, and then process it into an array with only tag names. Then use reduce to obtain an object with the tag name as the attribute name and the tag number as the attribute value. 2. Change the Object obtained in the previous step into a two-dimensional array with Object.entires(), and then process it with reduce to get the label with the largest number (compare tags[1] of each array and return tags[0] of array).
Answer code:
window.onload=function(){
// The maximum number of ideas is JS required to use reduce
const maxBy=function(list,tag){
return list.reduce(
function(x,y){
// Obtain the label with the largest number according to the reduce method
returntag(x)>tag(y)? x:y } ) }function getFrequentTag(){
// Get the array required by reduce
const tags=[...document.querySelectorAll(The '*')].map(x= >x.tagName).reduce((acc,tag) = >{ acc[tag]=acc[tag]? acc[tag]+1:1;
If the element exists in the array, the value is +1, otherwise the element is created and set to 1
return acc;// Get the object with the tag name as the attribute name and the number as the attribute value}, {})// The initial value is an object
return maxBy(Object.entries(tags),tag= >tag[1])
//tag=>tag[1] This function represents the second value of the return array, the number of tags
}
console.log(getFrequentTag());
}
Copy the code
Extension: How do I get the second most tags and the X most tags?
To further optimize the above solution, what we want to do is not to get the maximum, but to get arbitrarily large tags! Use the sort method to improve, sort the list array, and then get the corresponding position in the list array value.
Code:
// Get the x-th label
window.onload=function(){
// The maximum number of ideas is JS required to use reduce
const maxByx=function(list,tag,x){
list=list.sort((a,b) = >{
return tag(b)-tag(a);// The quantity is sorted from largest to smallest
})
return list[x];
}
function getFrequentTag(){
// Get the array required by reduce
const tags=[...document.querySelectorAll(The '*')].map(x= >x.tagName).reduce((acc,tag) = >{ acc[tag]=acc[tag]? acc[tag]+1:1;If the element exists in the array, the value is +1, otherwise the element is created and set to 1
return acc;// Get the object with the tag name as the attribute name and the number as the attribute value}, {})// The initial value is an object
return maxByx(Object.entries(tags),tag= >tag[1].1)
// The third parameter is used to specify the size of the object, in this case, the second largest
//tag=>tag[1] This function represents the second value of the return array, the number of tags
}
console.log(getFrequentTag());
}
Copy the code
Return maxByx(Object.entries(tags),tag=>tag[1],1), we only need to specify the third parameter value to get the number X tag we want. This completes the interview process of getting the maximum number of tags in HTML!
Thank you for reading, there are good suggestions please be sure to put forward, thank you, the author is also preparing for the interview recently!
Reference article:
How do I get the most frequent HTML tags on a page
JavaScript array deduplication