Basic Algorithms Scripting : where do i belong, cannot use forEach?[solved]

Basic Algorithms Scripting : where do i belong, cannot use forEach?[solved]
0

#1

I already passed this test, but i just wonder why i cannot use forEach for the solution. Below is not working :

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.sort(function(a,b){return a-b;});  
  
  arr.forEach(function(d,i){
    if(d>=num)return i;    
  });
  return arr.length;
}

So i have to change it like as follow in order to pass the test :

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.sort(function(a,b){return a-b;});  
  
  for(let i=0;i<=arr.length;i++){
    if(arr[i]>=num)return i;
  }
  return arr.length;
}

#2

The issue is that when you return i inside your forEach callback function, it is only returning for that callback function it is not a return for the getIndexToIns function.


#3

Ahh, correct, i managed to get the forEach solution to work as follows :

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.sort(function(a,b){return a-b;});  
  
  let found = false;
  let numIdx = 0;
  arr.forEach(function(d,i){
    if(!found && d>=num){
      numIdx = i;
      found = true;    
    }
  });
  return found?numIdx:arr.length;
}

getIndexToIns([40, 60], 50);

But i prefer the for loop solution since it returns once the index is found, no need to check until the end of array. Thank you again, that’s twice you helped me today.:+1:


#4

Hi Everyone !
I came up with the following solution.

Hope this makes sence.

function getIndexToIns(arr, num) {
    // Find my place in this sorted array.
    arr.push(num);
    let sortedArr = arr.sort((a, b) => (a > b) ? 1 : -1);
    return sortedArr.indexOf(num);
}

console.log(getIndexToIns([5, 3, 20, 3], 3));

#5