Reputation: 23
I have array with 20 random numbers (from -10 to 10) , I need to sort them . The even numbers must be in front of array. like let arr = [-2,3,6,-12,9,2,-4,-11,-8] must become arr = [-12,-8,-2,2,4,6,-11,3,9] here is my code:
let array = Array(20).fill().map(() => Math.round(Math.random() * 20) - 10);
console.log(array);
function moveEvenToFront(array){
let temp=0;
let a=0;
for(let i=0;i<array.length;i++){
if(array[i] % 2 == 0){
for (let j=i; j>a; j-- ){
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
a++;
}
}
return array;
}
moveEvenToFront(array);
I tried this function , but it doesn't works.
Upvotes: 2
Views: 387
Reputation: 41
function moveEvenToFront(array) {
let evenIndex = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] % 2 === 0) {
// Swapping the current element with the element at evenIndex
let temp = array[i];
array[i] = array[evenIndex];
array[evenIndex] = temp;
evenIndex++;
}
}
return array;
}
Upvotes: 0
Reputation: 386650
You could use a group for sorting even and odd numbers and then sort by value with a chained approach.
function sort(array) {
return array.sort((a, b) => Math.abs(a) % 2 - Math.abs(b) % 2 || a - b)
}
console.log(sort(Array.from({ length: 20 }, _ => Math.round(Math.random() * 20) - 10)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2
Reputation: 1031
Your best bet is to use Array.prototype.sort()
let array = Array(20).fill().map(() => Math.round(Math.random() * 20) - 10);
function moveEvenToFront(array) {
console.log(array);
const tempEven = array.filter(el => {return el % 2 === 0});
const tempOdd = array.filter(el => {return el % 2 !== 0});
const tempEvenSorted = tempEven.sort((a, b) => {
return a - b;
});
const tempOddSorted = tempOdd.sort((a, b) => {
return a - b;
});
return tempEvenSorted.concat(tempOddSorted);
}
console.log(moveEvenToFront(array));
A combination of filter() and sort(). First filter the evens and then the odds into different arrays. Then sort them separately and then add them together.
The sort()
function takes two arguments which are elements from your original array and must return a negative number, a positive number or zero and based on that creates a new sorted array and returns it.
Upvotes: 0
Reputation: 413767
You can use the .sort()
method and a comparator. The comparator function will have to first check the "evenness" of the two arguments. If they're both even or both odd, it'll then base the comparison result on the value:
array.sort(function(a, b) {
let aeven = !(a % 2), beven = !(b % 2);
if (aeven && !beven) return -1;
if (beven && !aeven) return 1;
return a - b;
});
A comparator function for the .sort()
method is passed two values from the array. The function should return:
Upvotes: 6