If first item of array matches condition move it to last position in array

Viewed 22

I have an array which I have sorted from smallest integer to largest. The array data comes from backend and will be random numbers

// example array from backend
const arr = [400,30,10,-1]

const sortedArray = arr.sort((a, b) => a - b)
// [-1,10,30,400]

If the first index of the array is equal to -1 I want to remove it from the first position in the array and append it to the last position of the array.

For example if array is [-1, 10, 30, 400] I want to return [10,30,400,-1].

Edit: I am looking for the safest possible way and unsure to use splice(), filter() etc

3 Answers

shift the first element off the array and push it on the end.

const arr = [400,30,10,-1].sort();
if (arr[0] === -1) arr.push(arr.shift());
console.log(arr);

After your code you can check first element is -1 and then slice and push -1 to it

if(arr[0] == -1){
  arr = arr.slice(1)
  arr.push(-1)
}

I might have exaggerated the solution, but I am guessing it might help someone.

const beData = [400, 30, 10, -1];

const sortedData = beData.sort((a, b) => a - b);

const newArr = sortedData.reduce((prevValue, currValue) => {
  if(currValue < 0) {
    prevValue[1].push(currValue);
  } else {
    prevValue[0].push(currValue);
  }
  return prevValue;
}, [[], []]);

const result = [...newArr[0], ...newArr[1]];

console.log(result);

Related