Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move array's one element to the end position and another one to the front position, and the others should be in the remaining position

I have Array: ['B', 'D', 'I', 'M', 'Other', 'T', 'U'].

I want to sort it in order: ['T', 'B', 'D', 'I', 'M', 'U', 'Other'].

How can I implement it with JavaScript?

like image 823
Denis Avatar asked May 30 '26 05:05

Denis


2 Answers

You could take an object with the order and sort the array.

const
    array = ['B', 'D', 'I', 'M', 'Other', 'T', 'U'],
    order = { T: -1, Other: Number.MAX_VALUE };

array.sort((a, b) => (order[a] || 0) - (order[b] || 0));

console.log(...array);
like image 174
Nina Scholz Avatar answered Jun 01 '26 20:06

Nina Scholz


Do you simply want this one, exact array to have two values moved elsewhere within the array? If so, you can do this, assuming your original array is called arr:

let startSplice = arr.splice(5,1)
let endSplice = arr.splice(4,1)

arr.unshift(startSplice[0])
arr.push(endSplice[0])

But I wouldn't really call this "sorting". Sorting in an array context typically implies that you have set rules on what you want the array order to be, for every element in the array, and that you may encounter various arrays that need to be sorted with these rules.

If your rules are simply "If I encounter a 'T', put it at the beginning of the array", and "if I encounter 'Other', put it at the end", then you could do this:

arr.sort((a,b) => {
    if (a === 'Other') {
        return 1
    } else if (a === 'T') {
        return -1
    } else if (b === 'Other') {
        return -1
    } else if (b === 'T') {
        return 1
    } else {
        return 0
    }
})
like image 22
JCollier Avatar answered Jun 01 '26 19:06

JCollier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!