Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

javascript - Javascript数组:删除另一个数组中包含的所有元素(Javascript arrays: remove all elements contained in another array)

I am looking for an efficient way to remove all elements from a javascript array if they are present in another array.(我正在寻找一种有效的方法来从javascript数组中删除所有元素(如果它们存在于另一个数组中)。)

// If I have this array: var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; // and this one: var toRemove = ['b', 'c', 'g']; I want to operate on myArray to leave it in this state: ['a', 'd', 'e', 'f'](我想对myArray进行操作,以使其保持这种状态: ['a', 'd', 'e', 'f']) With jQuery, I'm using grep() and inArray() , which works well:(使用jQuery,我使用的是grep()inArray() ,效果很好:) myArray = $.grep(myArray, function(value) { return $.inArray(value, toRemove) < 0; }); Is there a pure javascript way to do this without looping and splicing?(有没有这样做而不循环和拼接的纯JavaScript方法?)   ask by Tap translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the Array.filter() method:(使用Array.filter()方法:)

myArray = myArray.filter( function( el ) { return toRemove.indexOf( el ) < 0; } ); Small improvement, as browser support for Array.includes() has increased:(由于浏览器对Array.includes()支持增加了Array.includes()小改进:) myArray = myArray.filter( function( el ) { return !toRemove.includes( el ); } ); Next adaptation using arrow functions :(使用箭头功能的下一个适应:) myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...