var sortedSquares = function(nums) {
const squaredArray = []
for(let i=0; i<nums.length; i++){
squaredArray.push(Math.pow(nums[i], 2))
}
let arrayWithoutZeros = squaredArray.filter(ele => ele!=0 && ele !=1)
let arrayWithZeros = squaredArray.filter(ele => ele === 0 )
let arrayWithOnes = squaredArray.filter(ele => ele === 1)
let finalArray = arrayWithoutZeros.sort().reverse()
finalArray.unshift(...arrayWithOnes)
finalArray.unshift(...arrayWithZeros)
return finalArray
};
const nums = [-4,1,0,3,10]
sortedSquares(nums)
Output: [ 0, 1, 9, 16, 100 ]
So when i call the above function, I thought alright 0's and 1's end up in the end of array , well i wrote an array without it
But when writing this question i realized
var sortedSquares = function(nums) {
const squaredArray = []
for(let i=0; i<nums.length; i++){
squaredArray.push(Math.pow(nums[i], 2))
}
let arrayWithoutZeros = squaredArray.filter(ele => ele!=0 && ele !=1)
let arrayWithZeros = squaredArray.filter(ele => ele === 0 )
let arrayWithOnes = squaredArray.filter(ele => ele === 1)
let finalArray = arrayWithoutZeros.sort()
finalArray.unshift(...arrayWithOnes)
finalArray.unshift(...arrayWithZeros)
return finalArray
};
const nums = [-4,1,0,3,10]
sortedSquares(nums)
Output : [ 0, 1, 100, 16, 9 ]
Even sort doesn't return the desired output
What is the reason behind this, Is this because arrays are Objects in Javascript
unshiftdoes. It adds to the beginning of the array.sortedSquares()does all the steps it does? Why do you extract the0s and1s after squaring all the elements, then sort the other elements, and then prepend the0s and1s again? Just square all elements and sort them o.O -[-4,1,0,3,10].map(x => Math.pow(x, 2)).sort((a, b) => Math.sign(b - a))