2016-07-10 7 views
0

Helo,Фильтр для уникальных предметов с количеством предметов

Я использую следующий код, чтобы вернуть уникальный список категорий.

stadium_cats: function() { 
    let stadiums =[ 
     {"name":"Elland road","category":"football","country":"England"}, 
     {"name":"Principality stadiums","category":"rugby","country":"Wales"}, 
     {"name":"Twickenham","category":"rugby","country":"England"}, 
     {"name":"Eden Park","category":"rugby","country":"New Zealand"} 
    ]; 

    var categories = stadiums.map(function(obj) {return obj.category}); 
    categories = categories.filter(function(v,i) {return categories.indexOf(v) == i; }); 
    return categories; 
    } 

Когда я бегу выше я получаю массив уникальных stadium.category значений.

Может кто-то помочь мне продлить его, так что вместо массива возвращаемого я получаю массив объектов следующим образом:

[{"name":"football","count":"1"}{"name":"rugby","count":"3"}] 

Я хотел бы как имя и сколько раз он был показан?

Возможно ли это?

Большое спасибо, Dave

ответ

1

Только одна линия с ES6:

let stadiums = [{ name: 'Elland road', category: 'football', country: 'England' }, { name: 'Principality stadiums', category: 'rugby', country: 'Wales' }, { name: 'Twickenham', category: 'rugby', country: 'England' }, { name: 'Eden Park', category: 'rugby', country: 'New Zealand' }]; 
 
let result = [...new Set(stadiums.map(s => s.category))].map(c => ({ name: c, count: stadiums.filter(s => s.category === c).length })); 
 

 
console.log(result);

2

Вы можете сделать это с помощью forEach петли и объект в качестве дополнительного параметра.

let stadiums = [{"name":"Elland road","category":"football","country":"England"},{"name":"Principality stadiums","category":"rugby","country":"Wales"},{"name":"Twickenham","category":"rugby","country":"England"},{"name":"Eden Park","category":"rugby","country":"New Zealand"}]; 
 

 
var result = []; 
 
stadiums.forEach(function(e) { 
 
    if(!this[e.category]) { 
 
    this[e.category] = {name: e.category, count: 0} 
 
    result.push(this[e.category]); 
 
    } 
 
    this[e.category].count++; 
 
}, {}); 
 

 
console.log(result);

0

function stadium_cats() { 
 
    let stadiums = [{ 
 
    "name": "Elland road", 
 
    "category": "football", 
 
    "country": "England" 
 
    }, { 
 
    "name": "Principality stadiums", 
 
    "category": "rugby", 
 
    "country": "Wales" 
 
    }, { 
 
    "name": "Twickenham", 
 
    "category": "rugby", 
 
    "country": "England" 
 
    }, { 
 
    "name": "Eden Park", 
 
    "category": "rugby", 
 
    "country": "New Zealand" 
 
    }]; 
 

 
    var cat_arr = []; 
 
    var cats = {}; 
 
    var stadium; 
 

 
    for (var i = 0; i < stadiums.length; i++) { 
 
    stadium = stadiums[i]; 
 

 
    if (typeof cats[stadium.category] == 'undefined') { 
 
     cats[stadium.category] = { 
 
     name: stadium.category, 
 
     count: 0 
 
     }; 
 

 
     cat_arr.push(cats[stadium.category]); 
 
    } 
 

 
    cats[stadium.category].count++; 
 
    } 
 

 

 
    return cat_arr; 
 
} 
 

 
console.log(stadium_cats());

0

Пока вы запрашивали версию ES6, для этого вы можете использовать закрытие.

let stadiums = [{ name: "Elland road", category: "football", country: "England" }, { name: "Principality stadiums", category: "rugby", country: "Wales" }, { name: "Twickenham", category: "rugby", country: "England" }, { name: "Eden Park", category: "rugby", country: "New Zealand" }], 
 
    result = []; 
 

 
stadiums.forEach((hash => a => { 
 
    if (!hash[a.category]) { 
 
     hash[a.category] = { name: a.category, count: 0 }; 
 
     result.push(hash[a.category]); 
 
    } 
 
    hash[a.category].count++; 
 
})(Object.create(null))); 
 

 
console.log(result);

Смежные вопросы