最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

removes elements from array javascript (contrary intersection) - Stack Overflow

programmeradmin2浏览0评论

Yesterday nigth I maked this question Delete elements from array javascript But I mistook, my explanation and my example were about an intersection between two arrays.
What I wanted to ask is about how remove elements on array that doesn´t exist on other array.
Example:

Array A=> [a, b, c, d]  
Array B=> [b, d, e]  
Array C= removeElementsNotIn(A, B);  
Array C (after function)-> [a,c]

Thank you very much.

Yesterday nigth I maked this question Delete elements from array javascript But I mistook, my explanation and my example were about an intersection between two arrays.
What I wanted to ask is about how remove elements on array that doesn´t exist on other array.
Example:

Array A=> [a, b, c, d]  
Array B=> [b, d, e]  
Array C= removeElementsNotIn(A, B);  
Array C (after function)-> [a,c]

Thank you very much.

Share Improve this question edited May 23, 2017 at 12:28 CommunityBot 11 silver badge asked Apr 18, 2015 at 9:14 Eloy Fernández FrancoEloy Fernández Franco 1,3722 gold badges25 silver badges47 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

You can use .filter() to selectively remove items that don't pass a test.

var c = a.filter(function(item) { 
    return b.indexOf(item) < 0; // Returns true for items not found in b.
});

In a function:

function removeElementsNotIn(a, b) {
    return a.filter(function(item) { 
       return b.indexOf(item) < 0; // Returns true for items not found in b.
    });
}
var arrayC = removeElementsNotIn(arrayA, arrayB);

If you want to get really fancy (advanced only), you can create a function that returns the filtering function, like so:

function notIn(array) {
    return function(item) {
        return array.indexOf(item) < 0;
    };
}
// notIn(arrayB) returns the filter function.
var c = arrayA.filter(notIn(arrayB)); 

2022 answer

There is one more alternative which is easier to read:

const c = a.filter(item => !b.includes(item))

Thanks Second Rikhdo full code:

var a = [1,2,3,4,5];
var b = [4,5,6,7,8,9];

var new_array = a.filter(function(item) { 
  return b.indexOf(item) < 0; // Returns true for items not found in b.
});
alert(new_array);
// results: array[1,2,3]

Demo: https://jsfiddle.net/cmoa7Lw7/

a1 = ['s1', 's2', 's3', 's4', 's5'];
a2 = ['s4', 's5', 's6'];
a3 = [];

function theFunction(ar1, ar2) {
  var ar3 = [];
  for (var i = 0; i < a1.length; i++) {
    if (ar2.indexOf(ar1[i]) != -1) {
      ar3.push(ar1[i]);
    }
  }
  return ar3;
}

a3 = theFunction(a1, a2);

document.getElementById('out').innerHTML = a3.toString();
<div id="out"></div>

发布评论

评论列表(0)

  1. 暂无评论