Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  7] [ 3]  / answers: 1 / hits: 15475  / 5 Years ago, tue, february 12, 2019, 12:00:00

I have two arrays in my program, one contains a list of strings that act as keys, the other contains objects that contain a key as well.



let classKeys = ['math', 'robotics'];
let classesInList = [{key : WIHUGDYVWJ, className : 'math'},{key : qwljdhkuqwdnqwdk, className : 'english'},{key : likubqwd, className : 'robotics'},];


I need to return another array that contains objects like classesInList only if the key (as the className property) exists in classKeys



For example, in this scenario, I would need to check the classKeys against the classesInList and create an array with two items :



[{key : WIHUGDYVWJ, className : 'math'},{key : likubqwd, className : 'robotics'}]


since english is not in the classKeys, it is deleted from the classesInList.
How would I go about this?



Side Note: I am using react native so I have access to es6 properties and functions.



I am completely stuck in this sense. No matter how simple this seems to be I just cannot find an answer.


More From » arrays

 Answers
1

Just use Array.prototype.filter and combine that with Array.prototype.includes. What you want to do is to filter the classesInList array of objects, and only select those whose className value are present in the classKeys array.





let classKeys = ['math', 'robotics'];
let classesInList = [{key : WIHUGDYVWJ, className : 'math'},{key : qwljdhkuqwdnqwdk, className : 'english'},{key : likubqwd, className : 'robotics'}];

let filteredClasses = classesInList.filter(cls => classKeys.includes(cls.className));

console.log(filteredClasses);




[#52610] Thursday, February 7, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
danyelletyanah

Total Points: 204
Total Questions: 109
Total Answers: 108

Location: Vanuatu
Member since Fri, Oct 22, 2021
3 Years ago
;