I possess an array containing objects of different lengths depending on the chosen city. How can I pinpoint the element that contains an object with a specific property?

My dilemma arises from the fact that the length of an array depends on the selected city, making it impossible to select elements using an index. In this scenario, I need to devise a method to choose elements based on the value of one of their properties.

In particular, I am interested in selecting elements containing objects with the property types: ['locality', 'political'].

For instance, consider the following results (excluding the first 7 array elements as they are irrelevant):

7:
    address_components: (3) [{…}, {…}, {…}]
    types: Array(2)
        0: "locality"
        1: "political"

8:
    address_components: (2) [{…}, {…}]
    types: Array(2)
        0: "administrative_area_level_1"
        1: "political"

Each element features a types property represented as an array. My current aim is to identify the element at index 7 based on types: ['locality', 'political'] rather than its index.

Unfortunately, I haven't figured out how to achieve this yet, so I haven't written any code segments.

[
  {
    "address_components": [
      ...
    ],
    "formatted_address": ...,
    "geometry": {
      ...
    },
    "place_id": ...,
    "plus_code": {
      ...
    },
    "types": [
      ...
    ]
  },
  ...
]

Answer №1

To locate the element containing all of the specified types, you can use the following code:

 array.find(item => ['locality', 'political'].every(type => item.types.includes(type)))

Answer №2

Let's take a closer look at the situation.

Dilemma: you possess an array of objects and must identify and retrieve the one with the appropriate types array.

Initially, we must inspect each object in the array — a for loop is suitable for this task. Specifically, utilizing the for(... of ...) pattern:

for(let object of array){
    /* perform actions */
}

Next, it's imperative to evaluate each object based on the defined criteria. Since examining each object's types property is essential, we will begin here:

for(let object of array){
    if(someKindOfTest(object.types)){
        return object;
    }
}

How can we conduct this evaluation effectively? Assuming we know the types we seek...

let requiredTypes = ["locality"];

for(let object of array){
    if(someKindOfTest(object.types)){
        return object;
    }
}

We can create a test that only succeeds if the object contains all specified types. This calls for another loop:

let requiredTypes = ["locality"];

for(let object of array){
    let hasAllRequiredTypes = true;

    //  check for each required type

    for(let requiredType of requiredTypes){
        if(!object.types.includes(requiredType)){
            // this object does not match a required type, disqualifying it

            hasAllTypes = false; // mark this object as disqualified
            break; // exit the loop over required types
        }
    }

    if(hasAllRequiredTypes) return object;
}

This process can be condensed into a more concise and "functional" form (@jonas-wilms answer serves as an excellent example), yet outlining the fundamental mechanisms and problem-solving approach behind devising such an algorithm proves beneficial.

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

Navigating Date Conversion within Component in Angular 2 Application

Searching for a way to update the display of certain dates in my Angular 2 application, I encountered a roadblock. Using the date pipe in conjunction with string interpolation wasn't viable due to the structure of my template code: <input class="a ...

The functionality of "subscribe()" is outdated if utilized with "of(false)"

My editor is flagging the usage of of as deprecated. How can I resolve this issue and get it working with of? public save(): Observable<ISaveResult> | Observable<boolean> { if (this.item) { return this.databaseService.save(this.user ...

Input a new function

Trying to properly type this incoming function prop in a React Hook Component. Currently, I have just used any which is not ideal as I am still learning TypeScript: const FeaturedCompanies = (findFeaturedCompanies: any) => { ... } This is the plain fun ...

Utilizing JavaScript for loops to extract the final element from an array

I am facing an issue with the second loop within a function that goes through a JSON file. The problem is that it only returns the last item in the array. I need to figure out how to fix this because the chart object should be created on each iteration, ...

What sets apart Vue-Test-Utils' "mount" from "shallowMount"?

Just to clarify, my experience with Vue, JavaScript, and web frameworks is still pretty fresh. Currently, I am working on getting more familiar with basic unit and component testing using Jest and vue-test-utils. I have gone through the documentation for ...

AngularJS allows users to seamlessly retain any entered form data when redirected, enabling users to pick up right where they left off when returning to the form

I am currently working on a user data collection project that involves filling out multiple forms. Each form has its own dedicated HTML page for personal details, educational details, and more. After entering personal details and clicking next, the data ...

The 'props.p' navigation in react-native is undefined

I have gone through various forums and discussions regarding this issue, but none of the solutions seem to work for me. For some reason, I am facing difficulties passing props to react-navigation when I attempt to navigate, resulting in the following erro ...

The MUI toggle button does not indicate the selected input despite being configured with a value

Although the MUI toggle successfully registers user input, the selected option is not highlighted when clicked. I have included a value parameter and implemented an onChange function to update the value parameter on change. Initially, it does highlight " ...

Manipulate JSON data structure with JavaScript

The initial JSON data: { "data": { "count_at_hub": [ { "hub": "A", "date": "", "size": "1", "count": 141 }, { "hub": "A", "date": "", "size": " ...

Methods for assigning values to a formControl using an array

I have an array of objects and I am attempting to loop through the array, dynamically setting values to a formControl and not displaying anything if the value is null. I have searched for similar solutions but haven't found any references or examples ...

Issue with Node Canvas/Resemble.js: The image provided has not finished loading during the load operation

Recently, I encountered a challenge while trying to utilize Resemble.js in a node environment. Despite some initial complications with installing canvas/cairo due to OS X Mavericks/XQuarts and Homebrew issues, I eventually succeeded. After making signific ...

Utilizing on() in conjunction with a map function

Currently, I am in the process of refactoring my code and have decided to revisit how I handle on events by utilizing mapping. Below is a snippet of what I currently have: $('img#sorc').on({ mousemove: function (e) { alert('tes ...

"Improve your Angular ngrx workflow by utilizing the sandbox pattern to steer clear of

Currently, I'm trying to determine whether my implementation of the ngrx and sandbox pattern is effective. Here's the issue I'm facing: getFiles(userId: number, companyId: number) { this.fileService.getFiles(userId, companyId).subscribe(re ...

Verify the changing text within a Span tag with the use of Selenium in Java

Can anyone assist me in creating a logic to verify a dynamic text? The text within the tag below is constantly changing (to 6 distinct words), and I need to validate if those 6 unique words match the expected text. Is there a method to do this verification ...

The regular expression pattern ((xn--)?[a-z0-9]+(-[a-z0-9]+)*.)+[a-z]{2,} is functional when used on regexpal.com, however, it does not yield the

Within the code snippet below, the regular expression in the "pattern" variable is specifically designed to only match the criteria mentioned in the comment (which requires a minimum of 1 letter followed by a dot, and then two letters). var link = "Help" ...

Using Javascript to automatically submit a form when the enter key is pressed

Can anyone help me with a password form issue? I want the enter key to trigger the submit button but it's not working for me. I understand that the password can be viewed in the source code, this is just for practice purposes. <!DOCTYPE html> & ...

The different types of property 'cacheLocation' do not match

I have been working on updating an old React app from JavaScript to Typescript gradually. I started by migrating the configuration file, but encountered an error when renaming it to .TS. Here is the error message: /Users/xx/yy/lulo/src/adalConfig.ts (13, ...

Imitation of three-dimensional camera rotation

I've been exploring the realm of creating 3D games using JavaScript and HTML's 2D canvas. I recently came across a helpful tutorial that guided me in setting up a basic interactive scene. Now, I'm facing a challenge in implementing the func ...

Tips for displaying consecutive information from a Sequelize query with associations in Node.js

Attempting to create a straightforward sequential output from a demo Node.js app and Sequelize has proven to be challenging for me. I'm struggling to comprehend how promises and Bluebird can assist me in achieving the desired result: User: John Doe ...

Is it possible to remove content from a Content Editable container?

JSFiddle <div contenteditable="true"> <p>Trying out editing capabilities of this paragraph.</p> <figure> <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/ima ...