I have an array of objects called rows
, where each object has a string property called name
.
I would like to get the longest name
. How can I filter rows
and grab the row with the longest name, or grab the name itself. Thank you!
Lodash or vanilla JS both work for my purposes. If there are 2 strings tied for the longest length, grabbing either string works for my purposes.
const rows = [ { name: "bar", }, { name: "foobar", }, { name: "ba", }, ]; const firstItem = rows.slice().sort((a, b) => (a.name.length > b.name.length? -1: 1))[0]; console.log(firstItem.name); // Outputs 'foobar'
Note: I'm slicing the array to avoid mutating it in place
This should work just fine:
rows.sort((x,y) => y.name.length - x.name.length)[0]
This will mutate the data. You can make a copy of it if you don't want to sort the original rows
array. But keep an eye out for not mutating any returned object either as that will mutate the original too. If you don't want that, then you need to do a deep copy.
For example,
const rows = [{name: 'abcde'}, {name: 'abc'}, {name: 'abcd'}]; // spreading rows will essentially make a copy of `rows` const result = [...rows].sort((x,y) => y.name.length - x.name.length)[0] console.log(result); // this will print `{name: 'abcde'}` result.name = 123; // mutating the resulting object after making a copy console.log(rows); // this will be mutated now
Same with slice()
and concat()
. They will make a shallow copy too.
Just use Array.prototype.reduce
and keep the longest string.
rows.reduce((longest, current) => longest.name.length > current.name.length ? longest : current);
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.