简体   繁体   中英

Selecting elements from an array based on another array values in JavaScript

Sorry for this basic question... I am relatively new to JS.

I have two arrays and want to select values from one based on the values of the other.

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.

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.

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. Use something else.

class is a reserved word in JavaScript . To achieve the expected output, you can use .filter to return elements where classes[index] have the value of 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. They are almost exactly the same, except for the e replaced by an underscore in the first solution. 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..

Thanks again for your help and time: :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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