[英]How to compare and extract arrays inside of another array
我正在編寫一個程序,需要比較數組中不同的生日日期,數組是這樣的:
birthdays = [1, [11,2], 2, [2,4], 3, [11,2], 4, [3,5], 5, [6,7], 6, [3,5], 7, [8,9]..]
偶數索引存儲學生人數,奇數位置以數組[月,日]的形式存儲他們的生日日期。 我需要返回一組具有唯一生日日期的學生(他們的生日日期只在數組中出現一次)。
這是我到目前為止的努力:
function find(birthdays) {
let array2 = birthdays.slice();
let unique_arr = [];
let element_comp;
for (let i = 0; i < birthdays.length; i++) {
birthdays.splice(i,1)//birthdays
array2.splice(i+1,1)//numbers
}
for(let i = 0; i < birthdays.length; i++){
element_comp = birthdays[i];
for(let j = 0; j < birthdays.length; j++){
if(i !== j &&element_comp.toString == birthdays[j].toString){
break;
}
if(j === birthdays.length - 1){
unique_arr.push(array2[i])
}
}
}
return unique_arr;
}
我的想法是將數組分成兩個子數組,一個存儲數字,另一個存儲生日日期。 然后我一一比較了生日日期數組的元素,看它們是否唯一。 如果我找到相同的日期,我會跳出內部並開始比較下一個,否則如果內部索引到達數組的末尾,我會將相同索引的數字數組的元素存儲到另一個數組中回來
Expected Result:[2, 5, 7...]
但它並沒有按預期工作,因為它每次都會從數組中跳出並且永遠不會存儲元素。 請解釋我哪里做錯了,謝謝
你可以用字典來做。 沒有嵌套循環
循環元素並查看dict append 中是否存在月份和日期組合month_date
學生到它,否則使用month_date
和append 創建一個新鍵,以使用當前學生數組的值進行dict
在此循環完成后,您可以遍歷 dict 鍵值並查看是否有任何鍵具有單個值然后采用這些值。
function find(birthdays) {
let unique_dates = {}
for (let i = 0; i < birthdays.length; i+=2) {
let key = `${birthdays[i+1][0]}_${birthdays[i+1][1]}`
if (!(key in unique_dates)) {
unique_dates[key] = []
}
unique_dates[key].push(birthdays[i])
}
let unique_arr = [];
for (let unique_date in unique_dates){
if (unique_dates[unique_date].length == 1) {
unique_arr.push(unique_dates[unique_date][0])
}
}
return unique_arr;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.