简体   繁体   English

如何使用map和foreach过滤数组中不在另一个数组中的元素

[英]How to filter elements in an array that are not in another array using map and foreach

I want to find the elements in an array that are not present in a second array, using only the .map() and .forEach() methods (without using .filter() or other methods) 我想仅使用.map().forEach()方法(不使用.filter()或其他方法)来查找第二个数组中不存在的元素。

What I tried : 我试过了

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <p id="res"></p>
        <script>
            var result = document.getElementById("res");
            var arr = [1,2,3,1,2,3,4];
            var scor = [2,3];
            x = arr.map(function(item){
              return scor.forEach(function(item1){
              if(item1 != item)
                return item;
                })
            })
           result.innerHTML = x;
        </script>
    </body>
    </html>

The answer should be [1,1,4] but I am getting [,,,,,,,] . 答案应该是[1,1,4]但我正在得到[,,,,,,,]

Where is my mistake? 我的错误在哪里?

Your outer function (the one you pass to .map ) returns nothing, so you end up with an array full of undefined s. 您的外部函数(传递给.map函数)不返回任何内容,因此最终得到一个充满undefined s的数组。

It's equivalent to 相当于

x = [1,2,3,1,2,3,4].map(function (item) {});

You should not use map for this, it creates entry for every element, that's why you get bunch of undefined . 您不应该为此使用map,它会为每个元素创建一个条目,这就是为什么您会得到一堆undefined的原因。

Array.prototype.reduce would be more convenient here: Array.prototype.reduce在这里会更加方便:

 var arr = [1, 2, 3, 1, 2, 3, 4]; var scor = [2, 3]; var x = arr.reduce(function(prev, curr) { if (scor.indexOf(curr) === -1) { prev.push(curr); } return prev; }, []); console.log(x); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM