简体   繁体   中英

How to get the last occurrence of the duplicated array in Javascript

I have an array with duplicates:

nameList = [{name:"name1", filename:"filename1"}, {name:"name2", filename:"filename2"}, {name:"name3", filename:"filename2"}]

and I want to retain only the unique item but the last item only. I want:

nameList = [{name:"name1", filename:"filename1"}, {name:"name3", filename:"filename2"}]

I have tried:

var flags = {};
resultNameList = nameList.filter(function(entry) {
    if (flags[entry.filename]) {
        return false;
    }
    flags[entry.filename] = true;
    return true;
});

but it retains only the first occurrence of the duplicate. How can I get the last occurrence?

Please help. Thanks.

Reduce an object indexed by the filename property, overwriting the previous item at that key in the accumulator if it exists - this ensures that after all iterations, the object's values are composed only of the latest occurrence of a given filename. Then take the values of the accumulator:

 const nameList = [{ name: "name1", filename: "filename1" }, { name: "name2", filename: "filename2" }, { name: "name3", filename: "filename2" }]; const output = Object.values(nameList.reduce((a, item ) => { a[item.filename] = item; return a; }, {})); console.log(output); 

Note that key-value pairs in an object must be separated by : , not = .

The input given in the comment below looks to work as desired too:

 const nameList = [{ name: "name1", filename: "filename1" }, { name: "name3", filename: "filename2" }]; const output = Object.values(nameList.reduce((a, item) => { a[item.filename] = item; return a; }, {})); console.log(output); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM