Jump to content

JAVASCRIPT - SEARCH IF A WORD IS INSIDE AN ARRAY


gustavon

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 comment
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 comment
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 comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...