[英]Create an array of sub-arrays with the value of an element and the number of times it has repeated in JavaScript
我試圖獲取一個數組(例如,一個年份數組),然后制作一個新的子數組數組,該數組首先告訴原始數組中的唯一元素,其次告訴它重復了多少次。
例如,假設我從一組數字開始[1999, 1999, 2000, 2005, 2005, 2005, 2015]
我希望我的函數返回一個數組,如[[1999, 2], [2000, 1], [2005, 3], [2015, 1] ]
因為重復了1999年兩次,不重復2000年,重復了2005年等等。
我可以成功地制作一個刪除重復項的新數組,但是在制作子數組時,我得到了一些奇怪的行為。
編輯
這是我自己的錯誤解決方案,以防萬一有人想指出我做錯了什么。
var populateYearsList = function(yearsDuplicate){
var uniqueYears = [];
for (var i=0; i < yearsDuplicate.length; i++){
if(uniqueYears.indexOf(yearsDuplicate[i]) == -1){
uniqueYears.push(yearsDuplicate[i])
} else {
console.log("duplicate found") };
}
console.log (uniqueYears)
};
我遇到了嘗試將uniqueYears.push(yearsDuplicate[i])
更改為uniqueYears.push([ yearsDuplicate[i], 1 ])
,然后嘗試將console.log替換為某種遞增計數器的問題。
就像這樣簡單:
var input = [1999, 1999, 2000, 2005, 2005, 2005, 2015];
var uniq = [];
input.forEach(function(n){
if (uniq.indexOf(n)<0)
uniq.push(n);
});
var output = uniq.map(function(n){
return [n, input.filter(function(m){ return m == n }).length]
});
快速說明其運作方式
給定輸入數組,使用此映射將其唯一版本映射到新數組:
元素---> [元素, 原始數組中的出現次數 ]
編輯說明 :: 修復了先前的解決方案,該解決方案可能引入了重復元素。
這就是我要做的:
var input = [1999, 1999, 2000, 2005, 2005, 2005, 2015];
function numberOfOccurancesArray (input) {
var result = {};
for (var i = 0; i < input.length; i++) {
var currentYear = input[i];
// if there is an element with the name of the currentYear
if (result[currentYear]) {
// increace its prop `count` with 1
result[currentYear].count += 1;
} else {
// if not present, create it
result[currentYear] = {
year: currentYear,
count: 1
}
}
}
return result;
}
這是示例代碼: JsFiddle
var years = [1999, 1999, 2000, 2005, 2005, 2005, 2015];
var occurences = [];
for(var i = 0; i < years.length; i++ ) {
var year = years[i];
if(typeof occurences[year] === 'undefined') {
occurences[year] = 1;
} else {
occurences[year]++;
}
}
occurences = occurences.map(function(occurences, year) {
return [year, occurences];
});
console.log(occurences);
編輯 :更快的解決方案
var results = [];
var uniq = [];
var counts = [];
var i = 0;
for (i; i < years.length; i++) {
var year = years[i];
var indexOf = uniq.indexOf(year);
if (indexOf < 0) {
uniq.push(year);
counts[uniq.length - 1] = 1;
} else {
counts[indexOf] += 1;
}
}
i = 0;
for (i; i < uniq.length; i++) {
results.push([uniq[i], counts[i]]);
}
return results;
如果要使用功能范例,請將其簡化為字典,然后將鍵映射為元組。
var yearToCounts = input.reduce(function(counts, year) {
if (year in counts) {
counts[year]++;
} else {
counts[year] = 1;
}
return counts;
}, {});
return Object.keys(yearToCounts).map(function(year) {
return [year, yearToCounts[year]];
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.