Heim > Fragen und Antworten > Hauptteil
P粉8091101292023-09-06 17:33:17
var countries = [ {ChoicesID: 1, ChoicesName : '阿富汗'}, {ChoicesID: 2, ChoicesName : '阿尔巴尼亚'}, {ChoicesID: 3, ChoicesName : '阿尔及利亚'}, {ChoicesID: 4, ChoicesName : '安哥拉'}, {ChoicesID: 5, ChoicesName : '阿根廷'}, {ChoicesID: 6, ChoicesName : '亚美尼亚'} ]; var answer = ['阿富汗','阿尔巴尼亚','阿尔及利亚']; var NewCountries = countries.filter(o => !answer.includes(o.ChoicesName)) console.log(NewCountries)
像这样?
P粉7901875072023-09-06 09:46:39
使用 filter
并删除如果 answer
中存在它。创建一个 answerSet
以进行 O(1) 的查找,否则可以使用 includes
,但 includes
的时间复杂度为 O(m)(其中 m 是 answer
数组中的元素数量,n 是 countries
数组中的元素数量)
使用 set
O(m) + O(n).O(1) = O(n)(给定 n>m)
使用 includes
O(n).O(m) = O(nm)
var countries = [{ChoicesID: 1, ChoicesName : 'afghanistan'},{ChoicesID: 2, ChoicesName : 'albania'},{ChoicesID: 3, ChoicesName : 'algeria'},{ChoicesID: 4, ChoicesName : 'angola'},{ChoicesID: 5, ChoicesName : 'argentina'},{ChoicesID: 6, ChoicesName : 'armenia'}]; var answer = ['afghanistan','albania','algeria']; const answerSet = new Set(answer) const newCountries = countries.filter(c => !answerSet.has(c.ChoicesName)) console.log(newCountries)