-2

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?

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
bita
  • 335
  • 2
  • 9
  • 22
  • [`sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – Rory McCrossan Apr 15 '19 at 10:07
  • No. I exactly want number `1` and `2` be at the end of my numbers. Not sorting them. – bita Apr 15 '19 at 10:09
  • Please fully explain the logic required, and not just "I want 1 and 2 at the end". What do 3 and 4 do, or 6 and 7? Also post the code you already have so we can help fix it. – Reinstate Monica Cellio Apr 15 '19 at 10:10
  • 1
    @bita It's still sorting them, you just need to provide your own function to create whatever sort logic is required. See 'compare function': https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Syntax – Rory McCrossan Apr 15 '19 at 10:13
  • I've removed the jQuery tag and added the Javascript tag. I've assumed Javascript because of the previous jQuery tag, but this is definitely not a jQuery question. Do correct it if you want to do this in a language other than Javascript. – Reinstate Monica Cellio Apr 15 '19 at 10:40

3 Answers3

0

Here's a solution to your issue.

  1. Loop over your array
  2. If it's a 1 or 2 append it to temporary array ab
  3. If it's a different number than 1 or 2, append it to array aa
  4. Return joined arrays

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]))
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
0

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);
Styx
  • 9,863
  • 8
  • 43
  • 53
0

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
Kévin Bibollet
  • 3,573
  • 1
  • 15
  • 33