function getIndexToIns(arr, num) {
arr.sort((a, b) => a - b)
console.log(arr);
for (let i = 0; i < arr.length; i++){
if (num === arr[i]){
return arr.indexOf(num);
} else if(num < arr[i]){
arr.splice(arr.indexOf(arr[i]), 0, num)
return arr.indexOf(num);
} else if (num > arr[arr.length - 1]){
arr.push(num);
return arr.indexOf(num);
} else if (arr.length === 0){
return 0;
}
}
}
I’m stuck on the empty array scenario.
I’ve also tried using the push method to push the num in arr if arr.length === 0 and then with no luck doing a return arr.indexOf(num)… any other tips/tricks?
On a side note, can you use “switch” statements in functions?
Never mind. You did that already.
I was just wondering why u did if arr and i am not sure the length can be less than zero - an empty array will return true… Seems redundant
FYI - At this point in the code, you already know that arr is an array, so there is no need to check if it exists? Why? Because if it was not an array, the first line in your function would error out.
Also, your first if statement code block could be greatly simplified. If the array is empty, then you already know what index should be returned. It will always be the same number. There is no reason to push a single element to an empty array and then find the index of the single element. If there is only one element in the array, the desired index of that one element is known.
It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.
We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.
You can post solutions that invite discussion (like asking how the solution works, or asking about certain parts of the solution). But please don’t just post your solution for the sake of sharing it.
If you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.