tekac tekac - 6 months ago 41
Javascript Question

Javascript Insert into Array and return Index Position

function getIndexToIns(arr, num) {
arr.sort(function(a,b) {
return a-b;
});
for (var i=0;i<arr.length;i++) { // cycles through the array
if (arr[i] >= num) { // if array value is bigger than num
return i; // return index pos of num bigger than value
}
else if (arr[i] === undefined) { // if not found
arr.push(num); // push to array
return arr.indexOf(num); // return index pos of new num <-- should return 3 in this case
}
}
}

getIndexToIns([2, 5, 10], 15);


//getIndexToIns([2, 5, 10], 15) should return 3.

The mission of this is to sort an array, and return the index value of (arg2) if it were in the array.
EX: getIndexToIns([10, 20, 30, 40, 50], 35) should return 3.

What I'm having trouble with, is if the (arg2) is not found in the array, to push it into it..and return its index value. I can't seem to make it work.
Any ideas?

Answer

Another way to do it:

function getIndex(arr, num) {
  return arr.concat(num).sort(function(a, b) {
    return a - b;
  }).indexOf(num);
}

Sure there a few ways to do this but the fix in your code is below:

Working Example

function getIndexToIns(arr, num) {
  arr.sort(function(a,b) {
    return a-b;
  });
  for (var i=0;i<arr.length;i++) { // cycles through the array
    if (arr[i] >= num) { // if array value is bigger than num 
        return i; // return index pos of num bigger than value
    }
    if (i === arr.length - 1) { // if not found 
        arr.push(num); // push to array 
        return arr.indexOf(num); // return index pos of new num <-- should return 3 in this case
    }
  }
}

in your code you checked to see if (arr[i] === undefined) that will never happen, so instead check to see if you are at the end of the array, and if so, that means you haven't found your number, and then you can push it and get the index.

Comments