简体   繁体   中英

Counting occurrences in multidimensional array

I have a multidimensional array that looks like this

[1:[1:mammal,2:cat,3:fur],
 2:[1:mammal,2:dog,3:fur],
 3:[1:mammal,2:cat,3:fur],
 4:[1:fish,2:trout,3:scales]]

I wish to count the number of occurrences of animal to return an array such as this

[cat:2,dog:1,trout:1]

I have been trying unsuccessfully with a for loop, is there a better way to do it?

Your syntax is not correct, it will be easier to return an object with key value pairs.

Here is an example using the reduce function:

 const animals = [['mammal', 'cat', 'fur'], ['mammal', 'dog', 'fur'], ['mammal', 'cat', 'fur'], ['fish', 'trout', 'scales']] function count (animals) { return animals.reduce((acc, arr) => { for (const item of arr) { acc[item] = acc[item]?== undefined: acc[item] + 1, 1 } return acc }. {}) } console.log(count(animals))

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