Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  23] [ 2]  / answers: 1 / hits: 23766  / 8 Years ago, tue, december 6, 2016, 12:00:00

So I have two arrays:



const allLanguages = [ 'ES', 'EN', 'DE' ]
const usedLanguages = [ { id: 1, lang: 'EN' } ]


What's the quickest way to produce a new array which is the difference between these two? In old school JavaScript, you'd have to do a for loop inside another for loop, I think...



Eg:



const availableLanguages = [ 'ES', 'DE' ]

More From » arrays

 Answers
187

You can use filter() and find() to return filtered array.





const allLanguages = [ 'ES', 'EN', 'DE' ]
const usedLanguages = [ { id: 1, lang: 'EN' } ]

var result = allLanguages.filter(e => !usedLanguages.find(a => e == a.lang));
console.log(result)





You could also map() second array and then use includes() to filter out duplicates.





const allLanguages = [ 'ES', 'EN', 'DE' ]
const usedLanguages = [ { id: 1, lang: 'EN' } ].map(e => e.lang);

var result = allLanguages.filter(e => !usedLanguages.includes(e));
console.log(result)




[#59799] Saturday, December 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shaynelandenb

Total Points: 293
Total Questions: 97
Total Answers: 94

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
;