Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting All Elements In An Array (Javascript)

I am trying to check if a string contains certain words which I had stored in an array... however I'm new to JS, so I don't exactly know how to check all of the elements inside the Array.

Here is an Example:

const fruits = ["apple", "banana", "orange"]

I am actually checking if someone sends swearwords in a chat.

if(message.content.includes(fruits)){executed code}

However my issue is when I check for fruits it does anything but when I check for a specific element in the array like fruits[0] //returns apple it will actually check for that... So my issue / question is how do I check the string for all of the elements in the array not just apples.

like image 214
PandaDev Avatar asked Jun 10 '20 04:06

PandaDev


People also ask

How do I get all the elements in an array?

The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements.

How do you check if all values in an array are equal in JavaScript?

In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.

How do you print an array in JavaScript?

To print an array of objects properly, you need to format the array as a JSON string using JSON. stringify() method and attach the string to a <pre> tag in your HTML page. And that's how you can print JavaScript array elements to the web page.

Which method in JavaScript does return a range of elements of an array?

slice() method returns the selected elements in an array, as a new array object.


1 Answers

Your usage of includes is wrong.

From MDN:

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

arr.includes(valueToFind[, fromIndex])

const fruits = ["apple", "banana", "orange"];
const swearWord = "orange";

// execute is available
if (fruits.includes(swearWord))
  console.log("Swear word exists.");
else 
  console.log("Swear word doesn't exist.");

To check the otherway, if string contains the array's swearword:

const fruits = ["apple", "banana", "orange"];
const swearWord = "this contains a swear word. orange is the swear word";

// execute is available
if (checkForSwearWord())
  console.log("Swear word exists.");
else
  console.log("Swear word doesn't exist.");

function checkForSwearWord() {
  for (const fruit of fruits) 
    if (swearWord.includes(fruit)) return true;
  return false;
}
like image 124
Shravan Dhar Avatar answered Oct 13 '22 11:10

Shravan Dhar