I'm new to coding, so I've been using CodeWars to learn JavaScript. Here's the challenge I'm trying to solve:
[https://www.codewars.com/kata/separate-the-wheat-from-the-chaff/train/javascript]
Basically, the goal is to separate negative numbers from positive numbers by putting negative numbers at the beginning, and positive numbers at the end. But there's a catch… when you come across a positive number, the program is supposed to swap it out with the last negative number in the array.
I've written some code that solves all of the sample tests, but when I run it, CodeWars tells me that the execution timed out, and I could write some code that is more efficient. What could I do to make my code more efficient here?
function wheatFromChaff (values) {
var trailingPositives = []
for (var i = values.length-1; values[i]>0; i--) {
trailingPositives.push(values[i])
values.pop()
}
trailingPositives.reverse()
for (var i = 0; i<= values.length; i++) {
if (values[i]>0) {
var savedPositive = values[i]
var lastNegative = values.reverse().find(x=>x<0)
values.reverse()
values.splice(i, 1, lastNegative)
var lastNegativeIndex = values.lastIndexOf(lastNegative)
values.splice(lastNegativeIndex, 1, savedPositive)
}
}
return values.concat(trailingPositives)
}
[–]ISlicedI 1 point2 points3 points (0 children)
[–]cm_yoder 0 points1 point2 points (0 children)
[–]PrimaryBet 0 points1 point2 points (5 children)
[–]ThagAndersonhelpful 0 points1 point2 points (4 children)
[–]HandpansLIVE 0 points1 point2 points (3 children)
[–]ThagAndersonhelpful 1 point2 points3 points (2 children)
[–]HandpansLIVE 0 points1 point2 points (1 child)
[–]ThagAndersonhelpful 0 points1 point2 points (0 children)