1

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.

2
  • A for loop sounds pretty elegant to me tbh. Commented Feb 21, 2021 at 21:02
  • what would be the list of resulting student numbers in class = 1? perhaps demonstrate what you have tried with the for-loop and push approach? Commented Feb 21, 2021 at 21:02

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.