suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Vorgang zum Entfernen von Objekten, die dem Array-Wert entsprechen

<p>Ich habe ein Objektarray und ein normales Array, und wenn ein Element im Objektarray einem Element im normalen Array entspricht, möchte ich es entfernen. Das verwirrt mich. </p> <p>Das habe ich bisher versucht: </p> <p> <pre class="snippet-code-js lang-js Prettyprint-override"><code>var states = [ {ChoicesID: ​​​​1, ChoicesName: 'afghanistan'}, {ChoicesID: ​​​​2, ChoicesName: 'Albanien'}, {ChoicesID: ​​​​3, ChoicesName: 'Algerien'}, {ChoicesID: ​​​​4, ChoicesName: 'angola'}, {ChoicesID: ​​​​5, ChoicesName: 'argentina'}, {ChoicesID: ​​​​6, ChoicesName: 'armenia'} ]; var answer = ['afghanistan','albanien','algerien']; var ChoicesName = new Set(countries.map(d => d.ChoicesName)); var NewCountries = [...ChoicesName, ...answer.filter(d => !ChoicesName.has(countries.find(o => o.ChoicesName === Antwort)))]; console.log(NewCountries);</code></pre> </p> <p>Die erwartete Ausgabe sollte wie folgt aussehen: </p> <pre class="brush:php;toolbar:false;">var NewCountries = [ {ChoicesID: ​​​​4, ChoicesName: 'angola'}, {ChoicesID: ​​​​5, ChoicesName: 'argentina'}, {ChoicesID: ​​​​6, ChoicesName: 'armenia'} ];</pre></p>
P粉985686557P粉985686557453 Tage vor466

Antworte allen(2)Ich werde antworten

  • P粉809110129

    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)

    像这样?

    Antwort
    0
  • P粉790187507

    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)

    Antwort
    0
  • StornierenAntwort