-3

Write a single function that outputs the “largest” phone number in an input array (if multiple numbers are equally large, return the last one). Assume that the phone numbers are strings of 10 digits separated by dashes.

I wrote a function to answer the questions above. It comes out undefined. can someone help me find the error please. I feel that i am close to the answer.

var largestNumber = function(strings) {
  var ints = strings.map(function(el) {
    return el.replace(/-/g, '').split('').reduce(function(previousValue, currentValue, currentIndex, array) {
      return previousValue + currentValue;
    });
  });

  console.log(ints);

  var largest = Math.max.apply(Math, ints);
  return strings[ints.lastIndexOf(largest)];
};

console.log(largestNumber(['111-111-1111', '111-111-1112', '111-111-1113']));
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Tyler
  • 41
  • 2

2 Answers2

0
ints.lastIndexOf(largest)

This part searches for the last occurence of largest in ints. However, largest will always be a number, but ints contains only strings. Therefore, the number isn’t found and undefined is returned. To fix this, convert largest back to a string:

ints.lastIndexOf(largest.toString())

Also, you don’t need to split the strings and concatenate them back together.

This code is working:

var largestNumber = function(strings) {
  var ints = strings.map(function(el) {
    return el.replace(/-/g, '');
  });

  console.log(ints);

  var largest = Math.max.apply(Math, ints);

  return strings[ints.lastIndexOf(largest.toString())];
};

console.log(largestNumber(['111-111-1111', '111-111-1112', '111-111-1113']));

Alternatively, you could map the strings to numbers:

var ints = strings.map(function(el) {
  return Number(el.replace(/-/g, ''));
});
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
0

Since you are already using reduce() why not use one reduce() to return the highest

var largestNumber = function(strings) {
    return strings.reduce(function(previousValue, currentValue) {
        return +currentValue.replace(/-/g,'') > 
               +previousValue.replace(/-/g,'') ? currentValue : previousValue;
    });
};

alert(largestNumber(['111-111-1111', '111-111-1112', '111-111-1113']));
charlietfl
  • 170,828
  • 13
  • 121
  • 150