Home > Software engineering >  Move array's one element to the end position and another one to the front position, and the oth
Move array's one element to the end position and another one to the front position, and the oth

Time:01-26

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?

CodePudding user response:

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);

CodePudding user response:

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
    }
})
  • Related