While there isnt an "out-of-the-box" underscore function, we can extend the base library with our own function using the _.mixin()
function.
The extension works by using the underscore _.indexOf()
function to return the index of an element that matches a predicate. We then use the native JS splice
function, to remove 1
item at the returned index (Note that this will leave the array unaffected if _.indexOf
returns -1
). As per the docs, splice
, returns an array of all elements that were removed. We, lastly use the native JS concat
function, which merges two (or more) arrays together, to put the returned value from the concat
on to the end of the supplied array (arr
).
UnderscoreJS extending
(function(_) {
"use strict";
_.mixin({
moveToEndWhere: moveToEndWhere
});
/**
* @function moveToEndWhere
* @desc Searches an array for the first item matching a predicate, and moves the matched element to the end of the array
* @param {array} arr Array to be searched and altered
* @param {function|object} predicate Function or object used to search for matching element
* @returns {array} Updated array
* @memberof _.mixin
*/
function moveToEndWhere(arr, predicate){
return arr.concat(
arr.splice(
_.indexOf(arr, predicate)
, 1
)
);
}
})(_);
Usage
var data = [
{"id":"4","name":"Boaz"},
{"id":"2","name":"Shareen"},
{"id":"3","name":"Simon"},
{"id":"1","name":"Miriam"}
];
data = _.moveToEndWhere(data, {"id":3});