Interview front-end array deduplication, I will ask these 3 small questions

Regarding deduplication of arrays, it is already a clichéd question. There are already N articles about deduplication of arrays on the Internet. Therefore, anyone who can read this blog, we are all destined. I hope that in 2023, you can ride the wind and waves, Hit the sea. In general interviews, data deduplication is also a must-ask question. I usually ask the following three small questions.

 

Table of contents

1. Please talk about the usage scenarios of array deduplication projects 

1. Time axis

2. Example of front-end bank territory display

Second, let’s talk about several implementation methods of array deduplication 

1. Type 1

2. Type 2 

3. Type 3 

4. Type 4

5. Type 5 

6. Type 6 

3. Which one do you like to use the most?

I first liked this simple 

Now like this object form

4. Share a case of mine

Here is one of my success stories:


1. Please talk about the usage scenarios of array deduplication projects 

Before asking the question of deduplication of arrays, I will politely ask, do you often use deduplication of arrays? Generally, the answers I get are of course commonly used, (maybe he also wants to say, I must use it frequently, I use it every day, and I have been using it all the time. Just now when I was preparing for the interview, I also looked at several implementation methods for deduplication of arrays. ). Then I asked: Please tell me about the project scenario of deduplication of arrays.

He pondered for a while, did not speak, and then said embarrassingly: Once an array returned by the server contained duplicate data, so I used the array to deduplicate. I asked: Can you talk about the general scene, needless to say too detailed. Then he ignored me.

Let me talk about two scenarios where array deduplication will be used.

1. Time axis

 Let me just give you an example here. In fact, if you find a real example when you make it into a real website, you must do style beautification. In this timeline example, the year, month, and day are used as the summary point of the timeline, and the subitems of the summary point are the list contents to be recorded at this time. In this case, the return from the server must be in the form of an array, and the data format is roughly like this:

data = [
      {
        time: '2022-12-21 08:03:34',
        title: '使用css3实现一个超浪漫的新年倒计时'
       },
       {
         time: '2023-01-02 23:50:55',
         title: '我辛辛苦苦做了一个月的项目,组长年底用来写了晋升PPT'
        },
        {
          time: '2023-01-03 22:36:01',
          title: '内卷对于2022是一种无奈,也是一种修行'
        },
        {
           time: '2023-01-03 23:42:38',
           title: '前端bug每次都比后端多,我总结了5点原因'
        },
]

Note that because everyone's blog or a writing process must be a long-term process, the data must be indeterminate, and there may be paging, so it is impossible for the server to pre-organize the data into what the front end needs. , so at this time, the year, month, and day part of the data becomes a repeated part that needs to be deduplicated. After deduplication, it is used to display the summary points of this case

2. Example of front-end bank territory display

There are many websites that have such a page, and the bank's territory is displayed, because there are many large and small banks all over the country, we need to display it like this:

 Most of the time, the server will not first extract Beijing, Tianjin, Shanghai and other territories into the key value form of the map. For some reasons, it is also returned to the front end in the form of an array, and most of the time this array is directly pulled from the database. The fetched data, which leads to the need for our front-end to do some array deduplication. The server-side data looks like this:

data = [
       {
           city: '北京',
           name: '北京银行1'
       },
       {
           city: '北京',
           name: '北京银行2'
      },
      {
           city: '北京',
           name: 'XX商业银行'
      },
      {
           city: '天津',
           name: '天津银行1'
      },
      {
          city: '天津',
          name: '天津商业银行'
      },
      {
          city: '天津',
          name: '港口商业银行'
     },
]

With such a description, do you think of many similar scenarios? In this case, the city field in the array is the object that needs to be deduplicated.

Second, let’s talk about several implementation methods of array deduplication 

Because in real projects, deduplication may not only deduplicate some numbers, but may also contain some mixed strings and numbers, so here we randomly think of a mixed array, for example:

var arr = ['2022-03-21', 3, 8, 5, 3, 4, 3, '2022-03-21', '2022-03-22', 8];

1. Type 1

The first is to define a new empty array, and then execute nested double loops to monitor if there are no elements in the empty array, and push them into the empty array. This method examines the primary use of continue, which is also an idea. The first empty array must have no content. We pus an element, skip the first loop, and then compare the loop for the second time. The code is as follows:

var newArr = [];
for (var i=0;i<arr.length;i++) {
	if (newArr.length === 0) {
		newArr.push(arr[i]);
		continue;
	}
	for (var j=0;j<newArr.length;j++) {
		if (newArr.indexOf(arr[i]) === -1) {
			newArr.push(arr[i]);
		}
	}
}

2. Type 2 

The second type is an improvement of the first type. It also defines an empty array, and uses indexOf to monitor whether an element is contained in the new array. The code is as follows:

var newArr = [];
for (var i=0;i<arr.length;i++) {
    if (newArr.indexOf(arr[i]) === -1) {
	    newArr.push(arr[i]);
    }
}

3. Type 3 

The third type is the set released after es6. The setting of the set itself is a non-repeating class array, so there are knowledge points for converting arrays and sets, and the conversion of set to array can be [...set] A form of deconstruction, it can also be the method of Array.from(set), the code is as follows:

var mySet = new Set(arr); // 非重复的类数组
			
// var newArr = Array.from(mySet); // set转数组
var newArr = [...mySet]; // 或者是这种解构方法

4. Type 4

 Using the built-in method of filter, filter receives a built-in function, and the function itself receives 3 parameters. item is equivalent to arr[i], index is equivalent to i index, and arr is the array itself. In some cases, arr needs to be passed in, but this The case is not passed in because it is relatively simple. Use indexOf to find the index for the first time, and return all the elements that appear for the first time in the original array to achieve the effect of deduplication. The code is as follows:

var newArr = arr.filter((item, index) => {
	return arr.indexOf(item) === index;
})

5. Type 5 

The fifth is to use the built-in includes method of the array to monitor whether an element is contained in the array. If you say this in the interview, it proves that you have at least sorted out the new properties of the array or some built-in methods, which is a good idea. Answer, the code is as follows:

var newArr = [];
for (var i=0;i<arr.length;i++) {
	if (!newArr.includes(arr[i])) {
		newArr.push(arr[i]);
	}
}

6. Type 6 

The sixth is to create a new map (or object) object, and use its unique key value to continuously create attributes in the map. Once an attribute is created, it means that the attribute value can be modified. Some operations, and the attribute is already the only element that is deduplicated, the code is as follows:

var obj = {}; // 对象的key值是唯一的
var newArr = [];
for (var i=0;i<arr.length;i++) {
	if (!obj[arr[i]]) {
		obj[arr[i]] = arr[i];
	}
}

3. Which one do you like to use the most?

 There are more than these implementation methods for array deduplication, right? Then you have mentioned so many kinds. In fact, every time you do a project, you only use one method in a certain scenario. It is impossible for this requirement. I use all of them Alright, so which one do you like to use the most?

I first liked this simple 

In fact, in the earliest days, I liked the first type, because the technology was too hot at that time, but thinking about it, it is also very hot now, so many times I dare not export dry goods, and I don’t have much dry goods. Second, the output came. It’s also quite a lot to repeat with everyone. There are so many knowledge points written, why do people like to read mine? And at that time, I still regarded the first implementation method as a treasure, showing off to others everywhere, and tried it repeatedly, haha, but then I saw that I was using the second method.

Now like this object form

Now, I prefer the sixth type, because combined with many project scenarios, in fact, during the development process, it is rare to bring over a pure array for deduplication. Most of the time, like the case mentioned above, deduplication is for understanding Coupling, use the deduplicated part as a large key value, and the value part, sometimes it is some sub-arrays, sometimes it is more arrays, so I prefer the sixth method, directly the original aggregated array, Untie it, and then process it into a map object form, and then perform some rendering on the page.

4. Share a case of mine

How did this interview question come about? It is because everyone is working slowly and constantly encountering pain points. The result summed up by countless people has gradually developed into an interview question. Therefore, the solution to the interview question is usually checked online, and it can be solved by memorizing it.

But some interviewers, if you don't answer well, they think: You come to the interview, there are so many answers on the Internet, why don't you memorize them all? Your answer was so smooth, he thought again: This guy must have been answered, it is exactly the same as what was said on the Internet.

Therefore, it is recommended that you combine the answers to the interview questions with your own project experience during the interview, and bring the interview results into the project experience to answer. Tell me your own experience, then I think the interviewer may be impressed by your sincerity.

Here is one of my success stories:

I interviewed a company before, interviewing front-end development, and they didn't ask front-end interview questions, and they said those questions. For example, for a piece of meat, Zhang San gave fake money, the boss went to exchange it for real money, and then lost the money and lost the meat, etc. Of course, there are other intriguing similar problems. How can my broken IQ solve so many broken problems so quickly, and for some questions, the more you think about it, the easier it is to fall into thinking, and the more you think about it, the more wrong your thinking seems to be.

I wrote this directly on the paper:

var num = 100; // this is the initial 100 yuan,

num += 200; // The num at this time is 300 yuan, which is the step where the boss gets meat money

I directly wrote this kind of question in the form of code, neatly wrote notes and handed it in.

Of course, you can also write: Refuse to do this kind of problem solving, I will leave!

Guess you like

Origin blog.csdn.net/xingyu_qie/article/details/128606812