我有兩組陣列,一組包含以月為單位的日期值(無序),另一組包含相應的月份值;
array1=['jan','mar','dec','jan','sep','nov','mar']
array2=[3,5,5,4,5,8,2]
正如所見,每個月都可以出現不止一次。
id 喜歡對這些資料進行聚類/排序以獲得 2 個顯示月份和相應總值的陣列,本質上,獲取與 1 月對應的所有值,將它們相加并將它們輸出到另一個陣列以及包含月份的第四個陣列,而不重復。就像是
array3=['jan','mar','sep',nov','dec']
array4=[7,7,5,5,8] //totals
uj5u.com熱心網友回復:
您可以使用字典來跟蹤相同的月份。如果幾個月重復,它將添加到字典中的值。
array1=['jan','mar','dec','jan','sep','nov','mar']
array2=[3,5,5,4,5,8,2]
res = {}
for(let i=0;i<array1.length;i ){
if(array1[i] in res){
res[array1[i]] = array2[i]
} else {
res[array1[i]] = array2[i]
}
}
array3 = []
array4 = []
for(let i in res){
array3.push(i)
array4.push(res[i])
}
uj5u.com熱心網友回復:
您可以在此處使用 new Map() ,然后僅映射以選擇必要的值。
array1=['jan','mar','dec','jan','sep','nov','mar']
array2=[3,5,5,4,5,8,2]
const months = new Map();
array1.forEach((month, index) => {
months.set(month, (months.get(month) || 0) array2[index]);
});
const array3 = Array.from(months, ([month]) => month);
const array4 = Array.from(months, ([month, summ]) => summ);
console.log(array3);
console.log(array4);
uj5u.com熱心網友回復:
這種方法也可以根據月份數進行排序。
let array1=['jan','mar','dec','jan','sep','nov','mar']
let array2=[3,5,5,4,5,8,2]
//this is for saving the index and final sorting after monthwise summing up values
monthsObj = {};
['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].forEach((name,index) => {monthsObj[name]=index})
function getSum(a1, a2){
let obj = {};
for(let i=0;i<a1.length;i ){
//if the month is not present in the obj
if(obj[a1[i]] === undefined) obj[a1[i]] = a2[i];
else obj[a1[i]] = a2[i]; //otherwise add to the previous month value
}
//sort based on month numbers
let sorted = [...Object.entries(obj)].sort(function(a, b) {
return monthsObj[a[0]]-monthsObj[b[0]];
});
let final1 = [], final2=[];
for(let i=0;i<sorted.length;i ){
final1.push(sorted[i][0]);
final2.push(sorted[i][1]);
}
console.log(final1, final2);
}
getSum(array1, array2);
uj5u.com熱心網友回復:
該Set物件允許您存盤任何型別的唯一值,無論是原始值還是物件參考。這樣,您可以省略陣列中的重復值。(您可以閱讀此資源以獲取有關 的更多資訊Set。)
該Object.values()方法回傳給定物件自己的可列舉屬性值的陣列,其順序與for...in回圈提供的順序相同。(唯一的區別是for...in回圈也列舉原型鏈中的屬性。)有關更多詳細資訊,您可以閱讀this
array1=['jan','mar','dec','jan','sep','nov','mar']
array2=[3,5,5,4,5,8,2]
const months = {};
array1.forEach((month, index) => {
months[month]=(months[month] || 0) array2[index];
});
const array3 = Array.from(new Set(array1));
const array4 = Object.values(months) ;
console.log(array3);
console.log(array4);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363672.html
標籤:javascript
