Javascript / ES2015,计算出现次数并将其存储为数组中的对象

时间:2016-10-11 20:32:09

标签: javascript ecmascript-6

我从JSON提要中提取数据,并尝试计算每个名称(name_class)出现的次数。

我想以下列格式返回一个对象数组,其中count表示名称出现的次数:

myArray = [{name:"John", count: 5}, {name: "Sarah", count: 2}, {name: "Oliver", count: 3}];

到目前为止,我有以下内容,但这不计算出现次数,只是将另一个对象添加到数组中;

   let namestUi = {
    renderNames(names){
        var counter2 = [];
        let namesFound = names.map((name) => {
          let {name_class} = name;

            if(counter2.name == name_class){
              counter2.count++;
            } else { counter2.push({name: name_class, count: 1}); }
        });
        console.log(counter2);
        return namesFound;
      }
    };

这是构建对象数组但不计算出现次数。

2 个答案:

答案 0 :(得分:1)

function count(names){
    // Count occurrences using a map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
    let map = new Map();
    for (let name of names) {
        map.set(name, (map.get(name) || 0) + 1);
    }

    // Transform to array of { name, count }
    let result = [];
    for (let [name, count] of map) {
        result.push({name: name, count: count});
    }

    return result;
}

count(["a", "b", "c", "a", "b", "a"])
// [{"name":"a","count":3},{"name":"b","count":2},{"name":"c","count":1}]

答案 1 :(得分:0)

使用计数器变量时存在一些问题。您可以像访问普通对象一样访问属性,但是将其定义为数组。此外,您的//Code import UIKit import AVFoundation var audioPlayer = AVAudioPlayer() class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let music = Bundle.main.path(forResource: "sound", ofType: "wav") do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! )) } catch{ print(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func playSound(_ sender: UIButton) { audioPlayer.play() } } 回调函数未返回任何值。

您可以使用此代码使用map按名称键入计数器,然后应用Map将该Map转换为您请求的对象数组:



Array.from