Move item in array to last position

后端 未结 5 1582
终归单人心
终归单人心 2021-02-02 08:11

I have an array of objects. I want to move a selected object to the last position in the array. How do I do this in javascript or jquery?

Here is some code I have:

5条回答
  •  星月不相逢
    2021-02-02 09:00

    Using an anonymous function you can pass in the array and the value to filter by.

    let concatToEnd = function (arr, val) {
            return arr.filter(function(x) {
                return x !== val; // filter items not equal to value
            }).concat(arr.filter(function(x) { // concatonate to filtered array
                return x === val; // filter items equal to value 
            })
        );
    }
    
    // invoke
    concatToEnd(array, 'parent_product_type');
    

    You could probably shorten this further:

    let concatToEnd = (arr,val) => arr.filter(x => x !== val).concat(arr.filter(x => x === val))
    

    This function filters the items which do not equal the value passed in, then concatenates the result (to the end of the filtered array) of another filter function which filters out the items which do equal the value you've passed in.

    This function essentially separates the array into 2 filtered parts and then concatenates them back together

    This hasn't been tested for your use-case, but I've used something similar to move all numbers of an array to the end of the index.

提交回复
热议问题