用另一个数组过滤一个数组-JavaScript

2022/1/29 11:34:18

本文主要是介绍用另一个数组过滤一个数组-JavaScript,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

假设我们有一个数组和对象,如下所示:

const main = [
   {name: "Karan", age: 34},
   {name: "Aayush", age: 24},
   {name: "Ameesh", age: 23},
   {name: "Joy", age: 33},
   {name: "Siddarth", age: 43},
   {name: "Nakul", age: 31},
   {name: "Anmol", age: 21},
];
const names = ["Karan", "Joy", "Siddarth", "Ameesh"];

我们需要编写一个JavaScript函数,该函数接受两个这样的数组,并对第一个数组进行过滤以仅包含那些名称属性包含在第二个数组中的对象。

示例

以下是代码-

const main = [
{name: "Karan", age: 34},
{name: "Aayush", age: 24},
{name: "Ameesh", age: 23},
{name: "Joy", age: 33},
{name: "Siddarth", age: 43},
{name: "Nakul", age: 31},
{name: "Anmol", age: 21},
];
const names = ["Karan", "Joy", "Siddarth", "Ameesh"];

const filterUnwanted = (main, names) => {
   for(let i = 0; i < main.length; ){
      if(names.includes(main[i].name)){//检测数组names是否包含main[i].name:
         i++;
         continue;//结束本次循环进行下次循环
      };
      main.splice(i, 1);//删除对应原数据
   };
};
filterUnwanted(main, names);
console.log(main);

这将在控制台上产生以下输出-

[
   { name: 'Karan', age: 34 },
   { name: 'Ameesh', age: 23 },
   { name: 'Joy', age: 33 },
   { name: 'Siddarth', age: 43 }
]



这篇关于用另一个数组过滤一个数组-JavaScript的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程