Consider a JSON like this
{
"products": {
"c1": {
"stock": 100
},
"c2": {
"stock": 200
},
"c3": {
"stock": 300
},
"c4": {
"stock": 400
},
"c5": {
"stock": 500
}
}
}
To find minimum of stock, i wrote code like this
var minStock=Math.min(
products.c1.stock,
products.c2.stock,
products.c3.stock,
products.c4.stock,
products.c5.stock
)
console.log(minStock);
now i want to know which is minimum whether c1 ,c2,c3,c4 or c5 based on stock values,say in this case
console.log("c1 is minimum with stock 100");
This is a solution with Array#reduce()
. It returns equal references, too:
var object = { "products": { "c1": { "stock": 200 }, "c2": { "stock": 200 }, "c3": { "stock": 300 }, "c4": { "stock": 400 }, "c5": { "stock": 500 } } }, result = function (o) { var keys = Object.keys(o); return keys.reduce(function (r, k) { if (o[k].stock < o[r[0]].stock) { return [k]; } if (o[k].stock === o[r[0]].stock) { r.push(k); } return r; }, [keys.shift()]); }(object.products); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); document.write(result.join(', ') + ' ' + (result.length === 1 ? 'is' : 'are') + ' minimum with stock à '+ object.products[result[0]].stock);
use Object.keys and array#reduce for quick and easy solution
var min = Object.keys(products).reduce(function(min, item) {
return products[item].stock < products[min].stock ? item : min;
});
console.log(min, 'is minimum with stock', products[min].stock);
Or Object.keys , array#map and array#sort
var min = Object.keys(products).map(function(item) {
return {product: item, stock: products[item].stock}
}).sort(function(a, b) {
return a.stock - b.stock;
})[0]
console.log(min.product, 'is minimum with stock', min.stock);
The alternative with Array.sort
function:
var obj = {
"products": {
"c2": {
"stock": 200
},
"c3": {
"stock": 300
},
"c4": {
"stock": 400
},
"c5": {
"stock": 500
},
"c1": {
"stock": 100
},
}
};
var products = Object.keys(obj.products);
products.sort(function(a,b){
return obj.products[a].stock - obj.products[b].stock;
});
console.log(products[0] + " is minimum with stock " + obj.products[products[0]].stock);
// c1 is minimum with stock 100
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.