Home > Software engineering >  How to shift the specific element in array at the end without sorting?
How to shift the specific element in array at the end without sorting?

Time:09-16

I was trying to shift array element which contain 0 elements at the very end whenever it was found in the array. So, I have the below array, just wanted to know how we can shift all 0 elements at the end without sorting the element. Non-zero element order should not get affected. I was able to place 0 elements at the end using the sorting method but was unable to other solutions to achieve the expected output below.

Can anyone look into that sample how we get the expected output?

Sample Array

const arr = [4,5,1,0,3,8,0,9,2,0,4]

Expected output

const arr = [4,5,1,3,8,9,2,4,0,0,0]

CodePudding user response:

You could do 2 filter

const arr = [4, 5, 1, 0, 3, 8, 0, 9, 2, 0, 4]
const specificElement = 0

const res = [
  arr.filter(el => el !== specificElement),
  arr.filter(el => el === specificElement),
].flat()

console.log(res)

Or 1 filter

const arr = [4, 5, 1, 0, 3, 8, 0, 9, 2, 0, 4]
const specificElement = 0

let res = arr.filter(el => el !== specificElement)
res = res.concat(Array(arr.length - res.length).fill(specificElement))

console.log(res)

CodePudding user response:

A very simple way to do this is to create a new, empty array and then loop over the data from end to beginning, putting each element onto either the beginning (with unshift) or end (push) of the new array depending on whether it's 0.

const arr = [4, 5, 1, 0, 3, 8, 0, 9, 2, 0, 4];
const result = [];

for (let i = arr.length-1; i >= 0; i--) {
  if (arr[i] === 0) {
    result.push(arr[i]);
  } else {
    result.unshift(arr[i]);
  }
}

console.log(result);

  • Related