Using underscore
I would like to use this library more, so I'll collect how I have used it so far here...
Selecting objects from an array of objects:
var newArray = _.filter(array, function(e) {
return e.propertyName == search;
});
Instead of a loop-solution, like:
var newArray = [];
for (var i=0; i < array.length; i++) {
if (array[i].propertyName == search) {
newArray.push(array[i]);
}
}
return newArray;
If we have two arrays with the same type of objects and we want all objects in one array, except if they are in the second array:
// We have two arrays with the same types of objects.
// We want an array with the objects in array 1, except if the object exists in array 2.
resultArray = _.filter(array1, function(elementArray1) {
return !_.find(array2, function(elementArray2) {
return elementArray1.propertyName === elementArray2.propertyName;
});
});
If we want an array of ids (or some other property) from an array of objects:
var ids = _.pluck(array, "id");
}