Javascript - Verify the presence of two elements within an array

How can I ensure that both ages 10 and 18 exist in a JavaScript array of ages, rather than just one?

var ages = [3, 10, 18, 20];
ages.filter(age => age === 10 || age === 18); // returns 10 and 18
ages.filter(age => age === 10 && age === 18); // returns null

Using && doesn't guarantee the existence of both ages as it results in null. Is there a more elegant way to achieve this using a single statement, rather than combining separate find/filter checks?

In essence, if I check for the presence of 10 (exists) and 21 (does not exist) within the ages array, it should return null or false, indicating that one of them is missing.

Answer №1

To check if a value is included in an array, you can use the includes function:

var ages = [3, 10, 18, 20];
console.log(ages.includes(10) && ages.includes(18));

Another approach is to utilize the indexOf method:

arr.indexOf(searchElement)

arr.indexOf(searchElement, fromIndex)

var ages = [3, 10, 18, 20];
console.log(ages.indexOf(10)!=-1 && ages.indexOf(18)!=-1);

The findIndex method is also available for this purpose. It works similarly to indexOf, but with some distinctions:

Array.prototype.indexOf() requires a value as input, suitable for arrays of primitive types like Number, String, or Boolean.

Array.prototype.findIndex() takes a callback function as its first parameter, particularly beneficial when dealing with arrays of objects.

var ages = [3, 10, 18, 20];
var bool=ages.findIndex(a=>a==10)!=-1 && ages.findIndex(a=>a==18)!=-1;
console.log(bool);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A step-by-step guide to implementing Google Analytics Event tracking using PHP

Implementing Google Analytics Events in Javascript can be done using the following code: ga('send', 'event', 'test', 'test','value'); I am trying to incorporate this feature throughout my entire project. ...

Determine if Param is empty or not within the context of express.js

I am looking to create a table and populate it with all the parameters that are not empty in the parameter list provided below: http://localhost:5002/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="407535732b7008121931190539142 ...

The submit button remains unresponsive, yet upon removing its JavaScript code, it functions smoothly

This is the content of my index.html file. It contains JavaScript code. However, there seems to be a problem with the JavaScript validation as the Submit button does not perform any action when clicked. Surprisingly, when I remove the JavaScript code, the ...

What is the standard "placeholder" for a Select-box in Angular?

Currently in the process of developing a front-end web application with Angular 6, I have encountered a challenge. Specifically, I am working on creating a component that includes various select-boxes, resembling this setup: https://i.sstatic.net/6DmL9.pn ...

The Material UI Drawer stays closed despite the state being set to true

Currently, I am in the process of developing a WebApp utilizing React and Material UI. Despite following numerous tutorials on implementing the Drawer component and poring over the documentation, I am still struggling to grasp its functionality. Even thou ...

Sending parameters with $location.path() in AngularJS

Having trouble creating a redirection call in the controller with a numerical parameter. Here is the code I've been using: $location.path('/tasklist/:$rootScope.job_id'); I have also attempted the following: $location.path("/tasklist/",$r ...

Generating a collection of items using php

Transform array of items into a list of objects using PHP: [ Object { id=0, label="Myriel", group=1 }, Object { id=1, label="Napoleon", group=1}, .... .... ...

Modifying a single value within an array causes all other values within the array to become null

Within a nested structure of recycler views, I am facing an issue with editing text. Each edit text inside the inner recycler view affects the values in other edit texts when changed. To handle this, I have implemented an interface callback that communicat ...

Comparing DOM Creation in PHP and JavaScript

My website currently does not have any ajax requests, and here is a simplified version of my code: class all_posts { public function index($id){ $statement = $db->prepare("SELECT * FROM mytable WHERE id = :id"); $statement->exe ...

Incorporating Up and Down Arrows Based on Order Classification

Is there a way to add arrow indicators beside table column names in HTML code when sorting them in ascending or descending order? The data is retrieved from a database using AJAX and PHP, displayed in a table format. I have already created a function to so ...

Input form and select form collide in conflict when the "Enter" key is activated

My search box includes input forms and a select form with various options. The issue arises when using the place autocomplete feature from Google Maps alongside the select form. When the enter key is pressed after entering a location in the autocomplete fi ...

Javascript does not execute properly in Google Apps Script

Encountering issues while attempting to execute the code provided in Google app script. // 1.foldername = Folder name | 3.templateId = ID of the template to use // 2.SheetId = ID of spreadsheet to use. | 4.rootFolder = ID of the root fold ...

Ways to eliminate double slashes from URL in Next Js. Techniques for intercepting and editing a request on the server side using getServerSideProps

Looking to manipulate a server-side request - how can this be accomplished? http://localhost//example///author/admin/// The desired output is: http://localhost/example/author/admin/ In Next Js, how can duplicate slashes in a URL be eliminated and req ...

Struggling to get the knockout js remove function to function properly within a nested table structure

I've been encountering issues while trying to eliminate the formulation elements with the 'Delete comp' link. I can't seem to figure out why it's not functioning as expected. Moreover, the 'Add another composition' link o ...

Customizing the Header Navigation in Vue App.vue Across Various Views

Struggling to find the best approach for managing a header navigation in Vue 2 using Vuex with VueRouter. The main issue is creating a dynamic 'header' type navigation in App.vue. <div id="nav"> <!--Trying to create a dynamic ...

Unexpected server failure when connecting via socket.io to Node.js http-proxy

I'm encountering an issue with my Nodejs proxy server related to the dreaded socket hang up error. The server crashes every time I refresh the browser on 'app.example.com'. The connection seems fine and the page loads correctly, but the cra ...

How to access nested objects in JSON using MYSQL

How do I extract the array "1" within the "flavor" object from json code in mysql? Attribute name: settings {"without":{"usd":{"new":"5","old":"8"},"weight":"5"},"color":{"2","3"},"flavor":{"1","2"}} Furthermore, how can I retrieve the number inside the ...

"Resizing issue with multiple Highcharts not being resolved after selecting a new option from

Is there a way to resize multiple Highcharts on a webpage by clicking a button? When attempting to update the last chart using a dropdown menu and then clicking the resize button, an error message stating Uncaught TypeError: Cannot read property 'refl ...

Unlocking the Power of jQuery's toggle Method for Dynamic Functionality

For my project, I require numerous jQuery toggles to switch between text and icons. Currently, I am achieving this by using: $("#id1").click(function () { //Code for toggling display, changing icon and text }); $("#id2").click(function () { //Same co ...

Issue with the scope causing global variable not to update when button is pressed

I am facing an issue with a declared variable and jQuery code that is supposed to store a form's value as the value of that variable when a button is clicked, and then execute a function. var verb = ""; $( "#submit" ).click(function() { verb = $(& ...