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:
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.