I have some number :
0,0,0,5,1,2,8,10
I want to reorder the numbers .The numbers which are 1
and 2
should shift at the end of numbers. like this:
0,0,0,5,8,10,1,2
Is it possible?
I have some number :
0,0,0,5,1,2,8,10
I want to reorder the numbers .The numbers which are 1
and 2
should shift at the end of numbers. like this:
0,0,0,5,8,10,1,2
Is it possible?
Here's a solution to your issue.
1
or 2
append it to temporary array ab
aa
function extractOneTwo(arr){
let aa = []
let ab = []
for(i = 0; i < arr.length; i++){
if ([1,2].includes(arr[i])){
ab.push(arr[i])
}else{
aa.push(arr[i])
}
}
return([...aa, ...ab])
}
console.log(extractOneTwo([0,0,0,5,1,2,8,10]))
As @RoryMcCrossan has pointed, the Array.sort()
is a solution:
const arr = [0,0,0,5,1,2,8,10];
arr.sort((a,b) => {
if ([1,2].includes(a)) return 1;
if ([1,2].includes(b)) return -1;
return 0;
});
console.log(arr);
You will have to use Array#sort
as stated by many of us.
const numbers = [0, 0 ,0, 5, 1, 2, 8, 10];
/**
* Moves {toMove} values at the end of {arr}.
* @param {Array} arr
* @param {Array} toMove
* @returns {Array}
*/
function moveToEnd(arr, ...toMove) {
return [].concat(arr).sort((a, b) => {
if (toMove.includes(a)) {
return 1;
}
if (toMove.includes(b)) {
return -1;
}
});
}
console.log(moveToEnd(numbers, 1, 2)); // 0,0,0,5,8,10, 1,2
console.log(moveToEnd(numbers, 0, 8, 2)); // 5,1,10, 0,0,0,2,8