Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find longest string in array of objects by string property value

Tags:

javascript

I currently have an array that looks like this:

var array = [
  {
    "title": "Ender's Game",
    "genre": "Science Fiction",
    "year": 2008
  },
  {
    "title": "Harry Potter and the Goblet of Fire",
    "genre": "fantasy",
    "year": 2002
  },
  {
    "title": "Pride and Predjudice",
    "genre": "romance",
    "year": 1980
  }
]

I want to iterate through this array and find the length of the longest genre. I want something like this:

longestGenre(array);
15

Ive tried a few things including the following:

var getLongest = (array, key) =>
{
  let r = Object.values(array).reduce((res, curr) =>
  {
      if (!Array.isArray(curr))
          return res;

      let newMax = curr.reduce(
          (r, c) => c[[key]] && (c[[key]].length > r.length) ? c[[key]] : r,
          ""
      );

      res = newMax.length > res.length ? newMax : res;
      return res;

  }, "");
  longest = r;
  return longest;
}

And another approach I tried was this:

  for (key in obj){
      if (!obj.hasOwnProperty(key)) continue;
          if (obj.key.length > longest)
              longest = obj.key.length;
  }
like image 620
Mandalina Avatar asked Jun 01 '26 20:06

Mandalina


2 Answers

You don't need all those checks and nested loops, just map the array to the length of the genre, then take the maximum:

 const longestGenre = Math.max(...array.map(movie => movie.genre.length));

Or dynamically:

const longest = (key, array) => Math.max(...array.map(it => it[key].length));

console.log(longest("genre", /*in*/ array));
like image 93
Jonas Wilms Avatar answered Jun 03 '26 09:06

Jonas Wilms


You can also use reduce in a cleaner and more compact way.

Working snippet:

var arr = [
  {
    "title": "Ender's Game",
    "genre": "Science Fiction",
    "year": 2008
  },
  {
    "title": "Harry Potter and the Goblet of Fire",
    "genre": "fantasy",
    "year": 2002
  },
  {
    "title": "Pride and Predjudice",
    "genre": "romance",
    "year": 1980
  },
  {
    "title": "Pride and Predjudice",
    "genre": "asdasdasd asdasdasdsa asdasda",
    "year": 1980
  }
]
var longest = arr.reduce(function (a, b) { return a.genre.length > b.genre.length ? a : b; }).genre.length;
console.log(longest); 
like image 38
Mosè Raguzzini Avatar answered Jun 03 '26 10:06

Mosè Raguzzini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!