This is the 11th day of my participation in Gwen Challenge

preface

This is a kind of experience of the article, from the source of some basic algorithm ideas analysis, the use of a basic idea, or basic logic.

A class of algorithmic problems can be solved by using the unique property of object keys.

Array to heavy

Taking advantage of the unique properties of object keys, it is basic to perform array de-duplication.

function fn(data){
    let result = [], map = {};
    data.map(item= > {
        if(! map[item]){ result.push(item); map[item] =true; }})return result;
}

let newData = fn([1.2.1.1]); / / newData = [1, 2]
Copy the code

Although we already have the Set data structure in ES6, there is something to be inferred here by the unique characteristics of the object key, so pressing does not list.

Through a simple procedure above, it can be seen that in some specific scenarios, the use of the object’s key unique characteristics, can be less performance consumption, complete some data processing.

De-weight: Go a little deeper

Here, I will introduce a question sent to me by my friend. I will think about more questions than basic ones.

First, extract the keywords, remove the array weight, keep the same id w maximum, position unchanged.

Ok, so it’s still text after extraction, but if it’s a long description, extracting keywords can also quickly clarify what needs to be done.

solution

1. This step can be accomplished by taking advantage of the unique feature of the key in the object mentioned above.

2. Retain the object with the largest w in the same order as the id object.

3. It’s not just a matter of whether it exists in an object, but if it does, whose w value is greater.

Map ={id: w} map={1: 2}

In addition, the same position order, you have to update the data, remove the data, push again

function noRepeat(data){
	let result = [], map = {};
	
	data.map(item= > {
		if(map[item.id] && map[item.id] < item.w){
			for(let i = 0; i < result.length; i++){
				if(item.id == result[i].id){
					result.splice(i,1);
					result.push(item)
				}
			}
		} else if(! map[item.id]){ result.push(item); map[item.id] = item.w } })return result;
}	


let data = [{id:1.w:1}, {id:2.w:2}, {id:1.w:2}, {id:2.w:1}];
console.log( noRepeat(data)) 
Copy the code

Look at the results

It’s already working as expected.

conclusion

Isn’t it a good idea to consider the unique features of using object keys first when faced with the problem of de-duplication?

Although it is just one of the basic ideas in many algorithms, some simple data processing, especially de-duplication, works wonders.