Where do I belong - Reduce method

Where do I belong - Reduce method
0

#1

Tell us what’s happening:
I am using reduce function here, But I don’t know why… certain cases fail.

Your code so far

function getIndexToIns(arr, num) {
  arr.push(num);
arr.sort().reduce(function (curr,prev){
  return curr - prev;
});
return arr.indexOf(num);
}

getIndexToIns([40, 60], 50);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36.

Link to the challenge:


#2

Because you are not sorting correctly. Review the sort function documentation again, because you need to supply a function to compare the elements. If no function is provided, then the elements are sorted by converting them to strings and comparing strings in Unicode code point order.

For example, if I modify your original code above and put a console.log statement to see what array looks like after the sort, you will see the problem.

function getIndexToIns(arr, num) {
  arr.push(num);
  arr.sort();
  console.log(arr); // display arr after sort but before reduce is implemented  
  arr.reduce(function (curr,prev){
    return curr - prev;
  });
  return arr.indexOf(num);
}
getIndexToIns([3, 10, 5], 3); // returns 1 instead of 0

The above code displays:

[ 10, 3, 3, 5 ]

When each element is converted to a string for the sort, ‘10’ comes before ‘3’.


#3

Ahh, Thank you so much @RandellDawson, I found the mistake and correct that, Here my code :grinning:

function getIndexToIns(arr, num) {
  arr.push(num);
  arr.sort(function (a,b){
    return a -b 
  });               // sort function
  console.log(arr); // display arr after sort but before reduce is implemented  
  arr.reduce(function (curr,prev){
    return curr - prev;
  });
  return arr.indexOf(num);
}
getIndexToIns([3, 10, 5], 3); // returns 1 instead of 0