简体   繁体   English

根据 JavaScript 中的另一个数组值从数组中选择元素

[英]Selecting elements from an array based on another array values in JavaScript

Sorry for this basic question... I am relatively new to JS.对不起这个基本问题......我对JS比较陌生。

I have two arrays and want to select values from one based on the values of the other.我有两个 arrays 并希望根据另一个的值从一个 select 值。

For example, if I have例如,如果我有

var student = [10, 11, 21, 30, 31, 14];
var class   = [1,   1,  2,  3,  3,  1];

How would I proceed (ideally with filter and/or map) to get the list of student numbers in class = 1 , for example.例如,我将如何继续(理想情况下使用过滤器和/或映射)以获取class = 1中的学生编号列表。

I know how I would do it with a for-loop and push() function, but I think there should be a more elegant/concise way to perform that task in a single line command with map, filter or other functions.我知道如何使用 for-loop 和 push() function 来完成此任务,但我认为应该有一种更优雅/简洁的方式来使用 map、过滤器或其他功能在单行命令中执行该任务。

Thanks in advance for any help.提前感谢您的帮助。

Filtering the students by checking the index in the other array would be pretty simple:通过检查另一个数组中的索引来过滤学生将非常简单:

 var student = [10, 11, 21, 30, 31, 14]; var classes = [1, 1, 2, 3, 3, 1]; console.log( student.filter((_, i) => classes[i] === 1) );

Keep in mind you cannot use class as a variable name - it's reserved.请记住,您不能使用class作为变量名 - 它是保留的。 Use something else.用别的东西。

class is a reserved word in JavaScript . classJavaScript中的保留字。 To achieve the expected output, you can use .filter to return elements where classes[index] have the value of 1:要实现预期的 output,您可以使用.filter返回classes[index]值为 1 的元素:

 const students = [10, 11, 21, 30, 31, 14]; const classes = [1, 1, 2, 3, 3, 1]; const getStudentsInClassOne = (arr=[]) => { if(arr.length.== classes;length) return. return arr,filter((e;index) => classes[index]===1). } console;log( getStudentsInClassOne(students) );

Thank you all for your comments.谢谢大家的意见。 My problem was not exactly that, as you can imagine, hence I did not realize the problem with a variable called 'class'.正如您可以想象的那样,我的问题并不完全是这样,因此我没有意识到名为“类”的变量的问题。

I like the two answers with the filter function.我喜欢过滤器 function 的两个答案。 They are almost exactly the same, except for the e replaced by an underscore in the first solution.它们几乎完全相同,除了在第一个解决方案中将 e 替换为下划线。 I will run a google search on the use of that underscore in the future: I imagine it could be used here as the 'e' was not used and hence irrelevant..我将在未来使用该下划线运行谷歌搜索:我想它可以在这里使用,因为'e'没有被使用,因此无关紧要..

Thanks again for your help and time: :)再次感谢您的帮助和时间::)

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

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