How to use the spread operator (…) and Math.floor() In Javascript
In this approach, we utilize the spread operator (…) to create a copy of the original array. Then, we generate a random index within the range of the array length using Math.floor() and Math.random(). Finally, we return the randomly selected element from the copied array.
Example: In this example The function getRandomElement() returns a randomly selected element from an array by creating a copy, generating a random index, and accessing the element at that index.
let arr = ["apple", "banana", "orange", "grape", "kiwi"];
function getRandomElement(arr) {
// Create a copy of the original array using the spread operator
let copyArr = [...arr];
// Generate a random index within the range of the array length
let randomIndex = Math.floor(Math.random() * copyArr.length);
// Return the randomly selected element
return copyArr[randomIndex];
}
console.log(getRandomElement(arr));
Output
grape
How to check if an array includes an object in JavaScript ?
In JavaScript, an array acts like like list. It’s a way to group multiple items together under one name. You can store different things in your list, like numbers, words, or even other lists. Each item in the list has its own place, and you can access it using a number called its “index.”
We will check if an array includes an object or not in JavaScript. There are various methods to check whether an array includes an object or not.
These are the following approaches by using these we can check if an array includes an object in JavaScript:
Table of Content
- Using includes() Method
- Using some() Method
- Using filter() Method
- Using findIndex() Method
- Using Lodash _.find() Method
- Using the spread operator (…) and Math.floor():
- Using Array.prototype.find Method
Contact Us