简体   繁体   中英

Storing the quantity of values from an array into another array

I have got two arrays, one containing values with duplicates and the other empty:

let cart = [7, 7, 15, 21];
let quantity = [];

How can I get the number of times the values occur in the cart array and push it to the quantity array thus getting a result like this:

quantity = [2, 1, 1]

Where: 7 in the cart array is 2 in the quantity array, 15 and 21 is 1 in the quantity array respectively.

You can use a Map to keep the number of times item appeared in the cart and then use it to get the array in the form required

const cartItemsMap = new Map();

let cart = [7, 7, 15, 21, 7];

cart.forEach(item => cartItemsMap.set(item, (cartItemsMap.get(item) || 0) + 1));

let quantity = [...cartItemsMap.values()];

console.log(quantity); // [3, 1, 1] in the same order as of your cart items

We cannot use object here because the object won't keep the keys in order which I suppose you would want

An approach with a closure over an object for keeping indices.

 const cart = [7, 7, 15, 21], result = []; cart.forEach((indices => v => { if (v in indices) result[indices[v]]++; else indices[v] = result.push(1) - 1; })({})); console.log(result);

You can use .reduce to iterate over the cart while using a Map to store the number of occurrences of each number. In the end, you would return the values of this map:

 const getOccurences = (cart=[]) => cart.reduce((quantity,num) => { const count = 1 + (quantity.get(num) || 0); quantity.set(num, count); return quantity; }, new Map).values(); console.log(...getOccurences([7, 7, 15, 21, 7]) );

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