I want to find out the index of the element which is the lowest number in the array. For ex: function getIndexToIns([3, 2, 10, 7], 4) will return 2 because if 4 is inserted into the array, the array should be [2, 3, 4, 7, 10] following ascending order. And 4 has the index of 2.
And my code snippet is as below and it shows error "TypeError: newArr.sort is not a function"
function getIndexToIns(arr, num) {
newArr = arr.push(num);
newArr.sort((a, b) => a-b);
return newArr.indexOf(num)
}
getIndexToIns([2, 10, 4], 50);
console.log(getIndexToIns([2, 10, 4], 50))
What is wrong in my code snippet???
.push() modifies the array in place, it does not return a new array. So newArray isn't an array.
You can create a new array with something like:
let newArr = [...arr, num];
Or perhaps:
let newArr = arr.concat([num]);
See documentation for Array.prototype.push():
The push() method adds one or more elements to the end of an array and returns the new length of the array.
On top of that, push and sort methods mutate your original array. You should define your newArr like this:
const newArr = [...arr, num];
Then you can sort it and find out the index of element like you do it now.