Adelina Lipşa
Adelina Lipşa

Reputation: 30

How to sort even numbers ascending and odd numbers descending in an array?

I don't know how to sort the odd numbers in descending order on the right of the even ones. I'm kinda stuck here, I know I am missing something.

My output is like this: [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]

It should be like this: [2, 4, 6, 8, 10, 9, 7, 5, 3, 1]

var n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
n.sort(function(a, b) {
  return a % 2 - b % 2 || b % 2 - a % 2;
});
console.log(n);

Upvotes: 2

Views: 1229

Answers (5)

Denys Séguret
Denys Séguret

Reputation: 382168

A trivial and very expensive solution would be to build two arrays, sort them then concatenate them, but you can combine both tests and sort in place like this:

arr.sort((a,b)=> (a%2-b%2) || (a%2 ? b-a : a-b))

As you can see, the pattern for hierarchical sort is just

arr.sort(compareA || compareB) 

which you can generalize for more conditions.

let arr = Array.from({length:10}, (_,i)=>i+1)
arr.sort((a,b)=> (a%2-b%2) || (a%2 ? b-a : a-b))
console.log(arr)

Upvotes: 3

Maheer Ali
Maheer Ali

Reputation: 36574

You can use filter() to get different arrays of even and odd numbers and then sort them and join then using Spread Operator

var n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let odd = n.filter(x => x % 2).sort((a,b) => b-a);

let even = n.filter(x => !(x % 2) ).sort((a,b) => a-b);

let res = [...even,...odd]

console.log(res);

Upvotes: 1

Ele
Ele

Reputation: 33726

You can filter the odds and evens and, sort them and finally concatenate both arrays.

let n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let odds = n.filter((a) => a % 2 !== 0).sort((a, b) => b - a);
let even = n.filter((a) => a % 2 === 0).sort((a, b) => a - b);
let sorted = even.concat(odds);
console.log(sorted);
.as-console-wrapper { min-height: 100%; }

Upvotes: 1

Hien Nguyen
Hien Nguyen

Reputation: 18965

You can separate two array and merge by spread operator.

let n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let odd  = n.filter (v => v % 2);
odd.sort((a,b) => b-a);
//console.log(odd)
let even = n.filter (v => !(v % 2));
even.sort((a,b) => a-b);
//console.log(even);

console.log([...even,...odd]);

var n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
odd  = n.filter (v => v % 2);
odd.sort((a,b) => b-a);
//console.log(odd)
even = n.filter (v => !(v % 2));
even.sort((a,b) => a-b);
//console.log(even);

console.log([...even,...odd]);

Upvotes: 0

Hassan Saleh
Hassan Saleh

Reputation: 984

Did you try splitting the array into two arrays (one for even and one for odd) then sort each one as you like and join them back using the spread operator [...even, ...odd]

var n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var even = n.filter(a => a % 2 == 0).sort();
var odd = n.filter(a => a % 2 != 0).sort().reverse();
var numbers = [...even, ...odd];

Upvotes: 0

Related Questions