1

My task is to find the FIRST(not just the longest) occurrence of the longest string in Array. Tried following, but keeps returning the second occurrence...

function maxDigits (arr) {
var toStr = arr.map(value => String(value));
var longest = toStr.reduce(function (a, b) { return a.length > b.length ? a : b; })
return Number(longest)
}
maxDigits([12, 12345, 67890, 34])  // Getting 67890, target is 12345

Your suggestions with some explanation preferably. No jQuery, please. Much appreciated!

3
  • 1
    '12345'.length > '67890'.length ? '12345' : '67890'… which will it return? Commented Aug 7, 2017 at 10:23
  • const maxDigits = arr => arr.reduce((longest, item) => String(item).length > String(longest).length? item: longest); Commented Aug 7, 2017 at 10:35
  • arr.map(value => String(value)) === arr.map(String) Commented Aug 7, 2017 at 10:38

3 Answers 3

4

You want to keep the current string if the next string length is not greater, so instead of keeping the current string only if it's length is greater than the next one, keep it if the length is equal as well.

Use >= instead of > when comparing the lengths:

a.length >= b.length ? a : b

or take the next one only if the length of the current one is smaller than the next one:

a.length < b.length ? b : a

or take the next one only if it's length is greater than the current one:

b.length > a.length ? b : a

Example:

function maxDigits(arr) {
  var toStr = arr.map(value => String(value));
  var longest = toStr.reduce(function(a, b) {
    return b.length > a.length ? b : a;
  })
  return Number(longest)
}

var result = maxDigits([12, 12345, 67890, 34]);

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, Ori!! this helped a great lot plus clear explanation!
0

Or more simply put...

console.log(
    [12, 12345, 67890, 34]
        .map(function(a) { return a.toString() })
          .reduce(function (a, b) { return a.length >= b.length ? a : b; })
);

Comments

0

Only with a single line of reducing you may do as follows;

var nums   = [12, 12345, 67890, 34];
    result = nums.reduce((p,c) => Math.floor(Math.log10(p)) < Math.floor(Math.log10(c)) ? c : p);
console.log(result);

Note: Assuming that you have integers as shown in your example (instead of strings) then Math.floor(Math.log10(n)) will give you the number of digits of n less 1 which is sufficient for a comparison of successive array items and keeps the largest or first of equals.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.