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.
- acc (currently longest length int)
- 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);