Suppose there is an object array
arr=[
{
id:1,
content:'a'
},{
id:2,
content:'b'
},{
id:2,
content:'c'
},{
id:3,
content:'d'
},{
id:3,
content:'e'
},{
id:3,
content:'f'
},{
id:3,
content:'g'
},{
id:4,
content:'h'
},
]
I want to remove the same id and keep the last item of each id
arr=[
{
id:1,
content:'a'
},{
id:2,
content:'c'
},{
id:3,
content:'g'
},{
id:4,
content:'h'
},
]
Is there any better way? .
By convention, ES6 code
There is a problem here,
findIndex
is not supported by at least two browsers, so if it is not supported, you have to write one yourselfOther solutions
Classic solution, use Map
Because id is not a string, ES6’s
Map
class is used. When the amount of data is large, using a lookup table can significantly improve efficiency compared to linear search in a list.In fact, you can also use objects instead of maps, at least in this use case there will be no problem. Because there are no es6 features, we simply use es5 syntax. The code structure and logic are the same as the above paragraph
Weird solution, using integer id
Because it is an integer id, you can directly put it in the array according to this id. If the same ID is encountered, it will be replaced directly. If the ids are not consecutive, you need to filter out the empty elements at the end
There is another problem with this solution. It cannot maintain the order of the elements of the original array. Then someone will definitely think that the solution using Map can also reduce the code into similar code without making it so complicated. Of course, it may also lose the original order
Using arrow functions simplifies as follows:
There are already many answers here, but there is no mention of Array’s built-in function reduceRight. In fact, the questioner’s requirement is to retain the last digit of the same ID, which is very convenient to implement with reduceRight.
reduceRight starts looping from the end of your original array. The initial value here is an array. r[0] is used to store the Set of ids, and r[1] is used to store the result array. If there is no id in the Set, then add this id to Set and place this item at the head of the resulting array.
In the end, the topic owner’s needs were easily achieved, and the order was guaranteed.
Personally tested and effective
let newArr = [],
Please refer to it
You can refer to what I wrote on my blog. I wrote 8 methods on my blog. http://alfierichou.top/2017/0...