I’m looking for alternative solutions for returning specific items from an array.
[
["chrome", "72"],
["chrome", "71"],
["chrome", "70"],
["edge", "18"],
["edge", "17"]
]
How would I return the oldest version of each browser, e.g. [ [ "chrome", "70" ], [ "edge", "17" ] ]
?
I currently have a filter for chrome
and a filter for edge
, etc. But I wonder if there’s a cleaner way of achieving the same result.
You can use reduce
and min
const data =
[ ["chrome", "72"]
, ["chrome", "71"]
, ["chrome", "70"]
, ["edge", "18"]
, ["edge", "17"]
]
const result =
data.reduce
( (acc, [ browser, version ]) =>
({ ...acc, [browser]: Math.min(version, acc[browser] || Infinity) })
, {}
)
console.log(result)
// { "chrome": 70
// , "edge": 17
// }
console.log(Object.entries(result))
// [ [ "chrome", 70 ]
// , [ "edge", 17 ]
// ]
If you want the latest version, use max
instead -
const result =
data.reduce
( (acc, [ browser, version ]) =>
({ ...acc, [browser]: Math.max(version, acc[browser] || 0) })
, {}
)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments