Jump to content

JAVASCRIPT - SEARCH IF A WORD IS INSIDE AN ARRAY


Recommended Posts

I have this script and would like to make it search if just the word Mango is in the array and if it is true console.log the index of it. 

<!DOCTYPE html>
<html>
<body>
<h1>Array includes()</h1>
<p>Check if the fruit array contains "Mango":</p>
<p id="demo"></p>
<p><strong>Note:</strong> The includes method is not supported in Edge 13 (and earlier versions).</p>
<script>
var fruits = ["Banana is yellow", "Orange juice", "Apple is red", "Mango is orange"];
var n = fruits.includes("Mango");
console.log(n);
</script>
</body>
</html>

 

Link to post
Share on other sites

Hi there,

You might be able to use a combination of findIndex and includes. As below:

fruits.findIndex(element => element.includes("Mango"))

 

Link to post
Share on other sites
  • 1 month later...

Three different functions that demonstrate:

1 (wheat color background):  Successful match

2 (pink color background): Unsuccessful match

 

	<!DOCTYPE html>
<html>
	<style>
 #demo1 { background: wheat; }
 #demo2 { background: pink; }
</style>
	<body>
<h1>Array includes()</h1>
<!-- From: http://w3schools.invisionzone.com/topic/59508-javascript-search-if-a-word-is-inside-an-array/ -->
<p><strong>Note:</strong> The includes method is not supported in Edge 13 (and earlier versions).</p>
<p>Check if the fruit array contains "Mango":</p>
	<p id="demo"></p>
<pre id="demo1"></pre>
<pre id="demo2"></pre>
	<script>
  const lookFor = 'Mango';
  var fruits = ["Banana is yellow", "Orange juice", "Apple is red", "Mango is orange"];
  document.getElementById('demo').innerHTML = `Original Array: fruits<br> ${fruits.join('<br>')}`;
  checkFor('demo1', lookFor);
  checkFor('demo2', 'XXX');
	function checkFor(dw, lookFor) {
  document.getElementById(dw).innerHTML += `<p />Look for in 'fruits' array: ${lookFor}`;
	  var n = fruits.includes(lookFor);
  document.getElementById(dw).innerHTML += `<p />fruits.includes(${lookFor}): ${n}`;
	  var n1 = fruits.findIndex(element => element.includes(lookFor));
  document.getElementById(dw).innerHTML += `<p />fruits.findIndex(${lookFor}): #${n1} ${fruits[n1]}`;
	  var n2 = fruits.filter( function(x) { return (x.indexOf(lookFor) != -1) ? x : ''; } );
  document.getElementById(dw).innerHTML += `<p />fruits.filter(${lookFor}): `+n2;
}
</script>
</body>
</html>
	

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...