-1

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

DGB
  • 1,252
  • 2
  • 16
  • 32
  • 1
    Do you need this to happen only for the first element? Also can there be more than one -1 elements? – jateen Sep 12 '22 at 11:12
  • There will be no more -1 elements because I have used a function that doesn't return duplicates. -1 will be first always because it is the smallest possible integer. – DGB Sep 12 '22 at 11:14
  • 1
    So are you essentialy asking how to move the first item of an array to the end of an array? – Nick Parsons Sep 12 '22 at 11:15
  • Only if equal to -1. An array can be for example [3,4,5] or [-1,7,9] – DGB Sep 12 '22 at 11:17
  • @DGB you can access the elements in an array like `sortedArray[0]` so you'd need to check `if` it's -1 and then perform the move: [Fastest way to move first element to the end of an Array](https://stackoverflow.com/a/20385895) (like shown in the below answers) – Nick Parsons Sep 12 '22 at 11:20

3 Answers3

0

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);
Andy
  • 61,948
  • 13
  • 68
  • 95
0

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)
}
Singh3y
  • 336
  • 1
  • 7
0

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);
jateen
  • 642
  • 3
  • 13