I have the following array:
[[ "7", "4" ], [ "7", "43" ], [ "7", "4" ], [ "7", "" ], [ "6", "2" ], [ "7", "8" ] ]
How can I get the last occurrence of each distinct first element.
I would need the above array to be converted into:
[ [ "6", "2" ], [ "7", "8" ] ]
Use Map and use the first element as a key:
const data = [[ "7", "4" ], [ "7", "43" ], [ "7", "4" ], [ "7", "" ], [ "6", "2" ], [ "7", "8" ] ]; const result = Array.from(data.reduce((acc, item) => { acc.set(item[0], item) return acc; }, new Map()).values()); console.log(result);
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.