简体   繁体   中英

Push only one type of item in array

I want to be able to extract the values of the items bought at one specific location from my array. I want to be able to extract the value and put it into a seperate array, for example in the array posted below, I want to be able to get only the price for the item type Food and push it into a seperate array, how can I do that?

const array = [
    { Type: "Food", Price: "100" },
    { Type: "Entertainment", Price: "200" },
    { Type: "Food", Price: "80" },
    { Type: "Entertainment", Price: "150" }
];

Is there any easier way to get the total price of type Food?

You will want to reduce the data as a single sum. You will only add to the sum (running total) if they key equals "Food".

You start at zero, and add the parsed integer (since you do not care about decimals) price each item that has a key of "Food".

Edit: The logic of the reducer is as follows:

TOTAL + (DOES_KEY_MATCH? YES=PARSED_VALUE / NO=ZERO);

 const array = [ { Type: "Food", Price: "100" }, { Type: "Entertainment", Price: "200" }, { Type: "Food", Price: "80" }, { Type: "Entertainment", Price: "150" } ]; /** * Returns the sum of targeted values that match the key. * @param data {object[]} - An array of objects. * @param key {string} - The value of the key that you want to match. * @param options.keyField [key] {string} - The key field to match against. * @param options.valueField [value] {string} - The value of the matching item. * @return Returns the sum of all items' values that match the desired key. */ function calculateTotal(data, key, options) { let opts = Object.assign({ keyField: 'key', valueField: 'value' }, options || {}); return data.reduce((sum, item) => { return sum + (item[opts.keyField] === key? parseInt(item[opts.valueField], 10): 0); }, 0); } console.log('Total cost of Food: $' + calculateTotal(array, 'Food', { keyField: 'Type', valueField: 'Price' }));


If you want to handle floating values...

You can use parseFloat instead of parseInt and format the number with toFixed(2) .

 const array = [ { Type: "Food", Price: "100" }, { Type: "Entertainment", Price: "200" }, { Type: "Food", Price: "80" }, { Type: "Entertainment", Price: "150" } ]; function calculateTotal(data, key, options) { let opts = Object.assign({ keyField: 'key', valueField: 'value' }, options || {}); return data.reduce((sum, item) => { return sum + (item[opts.keyField] === key? parseFloat(item[opts.valueField]): 0); }, 0); } console.log('Total cost of Food: $' + calculateTotal(array, 'Food', { keyField: 'Type', valueField: 'Price' }).toFixed(2));

Use forEach() to iterate on array and add the prices of given type to get the total.

Use Number() to convert the price from string to number. This works even if the price has decimals.

 const array = [ { Type: "Food", Price: "100" }, { Type: "Entertainment", Price: "200" }, { Type: "Food", Price: "80" }, { Type: "Entertainment", Price: "150" } ]; function getTotalPrice(array, type) { let total = 0; array.forEach(item => { if (item.Type === type) { total += Number(item.Price); } }); return total; } console.log(getTotalPrice(array, "Food"));

Or use reduce() .

 const array = [ { Type: "Food", Price: "100" }, { Type: "Entertainment", Price: "200" }, { Type: "Food", Price: "80" }, { Type: "Entertainment", Price: "150" } ]; function getTotalPrice(array, type) { return array.reduce((total, item) => { if (item.Type === type) { total += Number(item.Price); } return total; }, 0); return total; } console.log(getTotalPrice(array, "Food"));

You will have to first filter the array with the type you want to manipulate. This will give you a new array with only the type you want, which you can then just sum the price of each item.

foodArray = array.filter(a => a.Type === "Food");
var totalPrice = 0;
foodArray.forEach(food => totalPrice = totalPrice + food.Price);

Please note that if "Price" is a string, you should first cast that into a number. If you don't do that you will end up with a concatenation of all Prices, instead of a sum.

You could use javascript function filter() , and use a function as callback using with the type.

const array = [
    { Type: "Food", Price: "100" },
    { Type: "Entertainment", Price: "200" },
    { Type: "Food", Price: "80" },
    { Type: "Entertainment", Price: "150" }
];
let type = 'Food';

var found = array.find(findType(type));

function findType(type) {
   return (item) => item.Type === type;
}
console.log(found);
// Object { Type: "Food", Price: "100" }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM