I am trying to sort an array:
var mapped = [{
wiFi: true,
megapixel: '20 MP'
},{
wiFi: false,
megapixel: '25 MP'
},{
wiFi: true,
megapixel: '25 MP'
},{
wiFi: true,
megapixel: '21 MP'
}];
I would like to sort it on both properties (wiFi first). This is a really simple version of what I am doing, but the properties can be decided by the user, so I have a function that looks a bit like this:
var fields = ['wiFi', 'megapixel'];
// Sort our mapped array
mapped.sort(function (a, b) {
// Loop through our properties
fields.forEach(function (field) {
// Get our value (skip the first)
var x = a[field.name];
var y = b[field.name];
// Switch on the type
switch (typeof x) {
// Boolean
case "boolean":
// Return our value
return x === y ? 0 : x ? -1 : 1;
// Default
default:
// Return our value
return x === y ? 0 : x < y ? -1 : 1;
}
});
});
but my array is not being sorted at all. Does anyone know why?
forEachcallback.fieldsuntil the end. Stop when you don't return 0.