0

I looked in the MDM documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array to see if the arrays had some method to determine the shortest element of or longer of an array, and I did not find the solution. Is there any way to make it as simple as possible, or should I create a function to achieve it? Is there another place where you look for information?

I EDIT the question: My intention is to find out the longest text string in the following array:var valores = [true, 5, false, "hola", "adios", 2]Only text strings are taken into account, not the numbers in the array

Forgive the confusion, I think there is no similar question, or I ran away, well look. Thank you.

gemita
  • 1,645
  • 2
  • 6
  • 8

1 Answers1

0

Use Array.reduce(). It's the easiest way to find the element with the longest item:

var valores = ["true", "false", "hola", "adios", "miercoles"];


var res = valores.reduce((prev, current) => {
  return (prev.length > current.length) ? prev : current
});

console.log(res);

If you only want the max length, it becomes a bit easier:

var valores = ["true", "false", "hola", "adios", "miercoles"];


var res = valores.reduce((prev, current) => {
  return Math.max(prev, current.length);
}, 0);

console.log(res);
Goodbye StackExchange
  • 21,680
  • 7
  • 47
  • 83
  • @gemita Use my first block of code to find the longest, and then follow the steps [here](https://stackoverflow.com/a/5767357/4875631). – Goodbye StackExchange Aug 02 '18 at 23:59
  • It works perfectly @FrankerZ, but I made an error when writing the question, because I need to remove the longest text string from this array: `var valores = [true, 5, false, "hola", "adios", 2]` Should I edit the question? Sorry for the language error – gemita Aug 03 '18 at 00:07
  • Yes, please edit the question and be as clear as possible. Explain why your answer is not a duplicate. – Goodbye StackExchange Aug 03 '18 at 00:09
  • @gemita Also, the function that I listed should still work correctly. `.length` returns undefined on ints/strings, so it should work as expected. – Goodbye StackExchange Aug 03 '18 at 00:14
  • Well, it does not work for me, because the result of `console.log (res)` is 2, and I need you to check only the text strings within the array, without evaluating the numbers, and without evaluating true and false. Only text strings – gemita Aug 03 '18 at 00:31