Determine if there is any item in a collection that includes a specified attribute found in a separate set

I've attempted various solutions for this issue and have searched around but I'm unable to get it to work.

I am dealing with 2 arrays and need to verify if any of the items in one array contain any of the strings from the other array.

const stepsShown = ["ref2", "ref7"];
const items = [
{ name: "item1", element: "ref1"},
{ name: "item2", element: "ref2"}
];
const refsExist = items.some((r) =>{stepsShown.indexOf(r.element);});

Based on this scenario, I anticipate refsExist to be true

I might be confused with my syntax! Can someone offer assistance please? :)

Answer №1

You're almost there, but remember to check for a non -1 value and remove the brackets from your arrow function.

If your arrow function has only one expression, you can omit the brackets:

items.some(r=>stepsShown.indexOf(r.element)!=-1);

However, if your arrow function contains statements or multiple expressions, you'll need curly brackets. In that case, make sure to include a clear return statement.

items.some(r=>{
    for(something;) { ... }
    return someValue;
});

Rather than using the less readable .indexOf(..)!=-1 test, you can simplify it by using includes:

items.some(r=>stepsShown.includes(r.element));

Answer №2

Discovering an element and verifying its existence can be done seamlessly.

const itemsToDisplay = ["section3", "section1"];
const elementsList = [
{ name: "itemA", id: "section1"},
{ name: "itemB", id: "section2"}
];
const foundElement = elementsList.find((element) => {    
    return itemsToDisplay.indexOf(element.id) > -1;
});

console.log(foundElement !== undefined);

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

Having difficulty changing the visibility of a div element

I am currently working on a project that involves jQuery and ASP.Net. My main goal is to create a button that can hide/show a div using jQuery. Below is the code that I have implemented: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLI ...

The role of providers in Angular applications

After creating a component and service in my project, I followed the documentation's instruction to include the service in the providers metadata of the component for injection. However, I found that it still works fine even without mentioning it in t ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

Upgrading to Bootstrap 5 and customizing the collapse button text upon click

I've spent a lot of time searching for a solution to my problem, but all the advice I found is for bootstrap 3 and 4, not version 5. Below is the code I am currently using: <div class="p-3">9 Members Online <a class="p-1 btn ...

React and Redux: The Search for Missing Props

I am embarking on a new project using a different technology stack for the first time. In my previous job, I inherited an existing project with everything already set up. However, I am facing issues as my props are coming up as undefined and I am unsure wh ...

Prevent Vue.js text input from displaying the v-model value

How can I prevent an input from displaying the value of its pre-defined v-model in Vue.js? For instance, suppose I have an input with "value" as its v-model, which has already been set elsewhere in the code. I would like to avoid showing this "value" ins ...

Is there a way to ensure the functionality of this code without exposing my API keys? I am currently developing an application using Node.js, Angular, and Express

I have come across an issue with my code where process.env is not working within a specific function. I need to find a way to call process.env without displaying my keys. If I don't add my keys, the API call won't function properly. What options ...

The mysterious workings of the parseInt() function

As I begin my journey to self-teach JavaScript using HeadFirst JavaScript, I've encountered a minor obstacle. The chapter I'm currently studying delves into handling data input in forms. The issue arises when I attempt to utilize the updateOrder( ...

Is Axios the sole option for API calls when utilizing Next.js with SSG and SSR?

Can someone clarify the best practice for data fetching in Next.js? Should we avoid using axios or other methods in our functional components, and instead rely on SSG/SSR functions? I'm new to Next.js and seeking guidance. ...

What steps can be taken to disable Angular's automatic trimming of fields?

Is there a global way to prevent Angular from automatically trimming input fields throughout the entire application? I know that I can avoid it for specific fields using the ngTrim directive, but it's not ideal to add this directive to every text fiel ...

PHP implementation for a static header layout

I am interested in learning how to update content without refreshing the header. I have created a simple example below. Header.php <html> <head> </head> <body> <ul> <li><a href="index.php" ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...

Enforce a limit of two decimal places on input fields using jQuery

Looking to limit an input field so that users can only enter numbers with a maximum of two decimals. Is it possible to achieve this using jQuery? Any way I could utilize the jQuery toFixed() function for this purpose? Thank you in advance! ...

retrieving elements from an array object results in an undefined value

Utilizing an API to retrieve holidays and their corresponding dates, I extracted values from a JSON file and organized them into an array of arrays. function getHolidays(){ (...) var ulHoliday = new Array(); var txt = JSON.parse(this.responseText); const h ...

AngularJS / Updating the URL only after the template's resolve property has been successfully resolved

Resolve plays a crucial role in preventing a template from being displayed based on certain conditional logic that deals with the result of a promise (whether it is solved or rejected). In my application, I implement it like this: .config(['$routePr ...

Connecting multiple TypeScript files to a single template file with Angular: A comprehensive guide

Imagine you are working with a typescript file similar to the one below: @Component({ selector: 'app-product-alerts', templateUrl: './product-alerts.component.html', styleUrls: ['./product-alerts.component.css'] }) expo ...

Is there a way to update page content without having to refresh the entire page?

My goal is to refresh specific content on a page without having to reload the entire page using JavaScript or jQuery. Since my project is built in PHP and JavaScript, I encountered this issue. Note : I want the page content to refresh when a user performs ...

Vuejs dropdown selections are not working as expected due to a bug

My dropdown menu is being populated with options based on an API response that looks like the following: {"value":"1371","label":"apple"},{"value":"1371","label":"banana"},{&qu ...

Creating a directive in AngularJS to automatically populate select options with custom values

As someone who is relatively new to creating directives, I am looking to develop a directive that will assist me in my application. What I aim to achieve is a select element directive that comes pre-populated with options and is self-contained. All I need ...

What is a sophisticated approach to overriding a jQuery method specifically within a plugin?

Today, my brain is in a bit of a fog where I can't seem to find an elegant solution to this issue. I've recently come into possession of a plugin that I need to tweak in order to pass an enabled or disabled state to it, allowing it to detach all ...