Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get random value from array if it doesn't exist in another array

I have two arrays and I want to get a random new value from Array1, if the value isn’t included in Array2 already.

const array1 = ["Banana", "Orange", "Apple", "Mango"];
const array2 = ["Banana", "Mango"];

const randomElement = array1[Math.floor(Math.random() * array.length)];

I have already have a existing variable called randomElement, that finds a random element in Array 1 but it doesn’t look at whether the element already exists in Array 2 or not.

Ideally the variable randomElement should only currently output either "Orange" or "Apple" since they are the ones missing in Array 2. How do I go on about this task the easiest?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to compute the array having elements in array1 but not in array2 first, you can do this using Array#filter and Array#includes:

const array1 = ["Banana", "Orange", "Apple", "Mango"];
const array2 = ["Banana", "Mango"];

const array = array1.filter(e => !array2.includes(e));
const randomElement = array[Math.floor(Math.random() * array.length)];

console.log(randomElement);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading