1

So I get an array of ints, and I'm supposed to find the one with the most digits, however if there are several of the same size (the longest size that is), I'm to return the first one.

I suspect I gotta do something with the index, but I just don't know what

function findLongest(array){
  let arr = array.toString().split(',')
  let result =  arr.reduce((acc,cur,index) => acc.length > cur.length ? acc : cur)
  return parseInt(result)
}

2 Answers 2

1

First let's take a look at reduce:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Option 1:

use acc.length >= cur.length ? acc : cur.

  1. acc (currently longest length int)
  2. cur (currentIndex)

If acc have bigger or same length then keep the acc else use cur.

var arr = [1, 22, 33, 4444, 5555, 6666, 123, 21];

function findLongest(array){
  let arr = array.toString().split(',');
  let result =  arr.reduce((acc,cur,index) => acc.length >= cur.length ? acc : cur);
  console.log(`first matching longest int: ${result}`);
  return parseInt(result)
}


findLongest(arr);

Option 2:

Since your function use reduce it will loop through the array (from left to right) and output the last one matching, you can use reduceRight to loop through the array from the right (reverse order). You will get the first matching one easily.

(thanks to @marzelin from the comments)

var arr = [1, 22, 33, 4444, 5555, 6666, 123, 21];

function findLongest(array){
  let arr = array.toString().split(',');
  let result =  arr.reduceRight((acc,cur,index) => acc.length > cur.length ? acc : cur);
  console.log(`first matching longest int: ${result}`);
  return parseInt(result)
}


findLongest(arr);

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

1 Comment

there's also reduceRight() function that starts from the right side of an array
0

Try the following, to get the max length in the list and then iterate until you find the first occurrence with that length:

x = [56, 783, 231, 2, 5213, 382, 232, 1232, 42, 54]
function findLongest(array){
    let arr = array.toString().split(',');
    let maxLen = Math.max.apply(Math, arr.map(function (el) { return el.length }));
    let result =  arr.reduce((acc,cur,index) => acc.length == maxLen ? acc : cur);
    return parseInt(result);
}


document.write(JSON.stringify(x)+"<br><br>"+findLongest(x))

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.