Strategies for sorting an array of objects based on specific attributes

Here is an array of objects containing finalists:

finalistsCollection = [
    { name: 'Ann' , sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}] },
    { name: 'Jack' , sections: [{id: '798', name: 'someName'}] },
    { name: 'Morgan', sections: [{id: '456', name: 'someName'}] },
    { name: 'Billy', sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}]}, 
    { name: 'Monica', sections: [{id: '798', name: 'someName'}] }
]

I am attempting to filter this array based on the id value. Initially, I created a filtering function that checks if a sections array has only one object:

filter(directionId) {
     filteredCollection = this.finalistsCollection.filter((item) => item.sections[0].id === directionId
}

After applying the filter, I attempted to use the map() function, but it still returned the entire array.

Answer №1

This example shows how to filter a collection based on a specific criteria:

let contestantsCollection = [
    { name: 'Ann' , sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}] },
    { name: 'Jack' , sections: [{id: '798', name: 'someName'}] },
    { name: 'Morgan', sections: [{id: '456', name: 'someName'}] },
    { name: 'Billy', sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}]}, 
    { name: 'Monica', sections: [{id: '798', name: 'someName'}] }
]

function filterById(idToFilter) {
     let filteredCollection = contestantsCollection.filter((item) => {
       for (const section of item.sections) {
         if (section.id === idToFilter) {
           return true
         }
       }
       return false
     })
     console.log(filteredCollection)
}

filterById('456')

Answer №2

I hope this solution is beneficial to you

let finalists = [
  { name: 'Ann' , sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}] },
  { name: 'Jack' , sections: [{id: '798', name: 'someName'}] },
  { name: 'Morgan', sections: [{id: '456', name: 'someName'}] },
  { name: 'Billy', sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}]}, 
  { name: 'Monica', sections: [{id: '798', name: 'someName'}] }
]

function filterResults(sectionId) {
  return finalists.filter(item =>
    item.sections.some(x => x.id === sectionId)
  );
}

console.log(filterResults('456'));

Answer №3

To simplify the condition, you can employ a neat little trick:

sections.map(section=>section.id).includes(directionId)

    finalistsCollection = [
        { name: 'Ann' , sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}] },
        { name: 'Jack' , sections: [{id: '798', name: 'someName'}] },
        { name: 'Morgan', sections: [{id: '456', name: 'someName'}] },
        { name: 'Billy', sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}]}, 
        { name: 'Monica', sections: [{id: '798', name: 'someName'}] }
    ]



    function filter(directionId) {
         return finalistsCollection.filter((item) =>
             item.sections.map(section=>section.id).includes(directionId))
    }
    
    console.log(filter('798'))
    console.log(filter('456'))
    console.log(filter('112'))

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

Calculating the total of selected values in Checkboxes and Selectors using KnockoutJS

I have already created this using jQuery. You can view it on JSFiddle: JSFiddle HTML: <div class="container"> <header> <h3>The Crazy Things We'll Do for Money</h3> <div class="small"><em>An ele ...

Having trouble locating the module 'monaco-editor/esm/vs/editor/editor.worker' while using create react app

I am currently facing some challenges running react-monaco-editor in my project despite following the documentation and making necessary adjustments to my files. Below is a snippet of my package.json file: { "name": "chatbot_compiler", "version": "0. ...

Angular: Radio button groups are not responding correctly when populated within a loop using ng-repeat

My goal is to populate multiple sets of radio buttons in a loop by combining the group name and index to ensure each set is uniquely grouped. However, I am facing an issue where only the last group in the loop has a checked radio button, while all other gr ...

Utilizing Sheets Queries to merge rows and columns of text seamlessly

Looking for a way to extract data from multiple rows and columns and display it neatly in a single cell? The dataset contains information about speakers and sessions, with the goal of having a formatted output in mind. Preferably, the output should list th ...

Creating a two-column grid layout using Bootstrap 4 is a simple and efficient process. Let's see how

I've been struggling to get this to display side by side in a two-column grid. Even after following Bootstrap tutorials, I can't seem to make it work. Check out the code below: <div class="row"> <div class="col-md-8 ...

How come my dimensions are not returning correctly when I use offset().top and scrollTop() inside a scrolling element?

Currently in the process of developing a web app at , I am looking to implement a feature that will fade elements in and out as they enter and leave the visible part of a scrolling parent element. Taking inspiration from myfunkyside's response on this ...

Ensure that the bootstrap-datepicker field is validated when it is changed

My goal is to validate the order_datePicker input field when it is filled by using bootstrap-datepicker. Although I have come across some answers on stackoverflow, I am unable to make it work on my own. I have been successful with other input fields using: ...

What is the most effective way to utilize zoom with an Orthographic projection?

I'm attempting to utilize THREE.OrbitControls for zooming in an orthographic projection, but I'm not achieving the desired outcome. I believe it may be possible to adjust the viewSize that is multiplied by left, right, top, and bottom to achieve ...

Modify the td attributes while retaining the extracted data values from the website

I'm currently utilizing this code to extract data from another website: $searchURL = "http://www.anotherwebsite.com"; $html = file_get_contents($searchURL); $patternform = '/(<tbody.*<\/tbody>)/sm'; preg_match_all($patternfor ...

Unable to trap error using try-catch block within an asynchronous function

I'm attempting to integrate a try-catch block into an async function, but I am having trouble catching errors with status code 400 using the code below. const run = async () => { const response = await client.lists.addListMember(listId, { ema ...

Issue with background overlapping

I am currently creating a questionnaire that consists of 10 questions and calculates a score called total. If the total < 10, I want the screen to turn red. However, this required me to remove the previous wallpaper that was set: /*body{ backgr ...

Utilize Nuxt.js context within a Vue plugin

I have a situation where I'm working with Nuxt.js and have two plugins set up. In order to gain access to the VueI18n instance from lang.js within validate.js, I am in need of some guidance. Is there anyone familiar with how this can be accomplished? ...

Designing a pop-up window for fetching data using AngularJS

I'm having trouble loading data into a modal window using AngularJS. I want the URL to change when a link is clicked and have the data load into a modal window instead of a new page. I attempted to use the jQuery Facebox plugin, but it doesn't s ...

Issue: ArrayBuffer failing to function properly in conjunction with Float64Array in NodeJS

Having some trouble with getting a Float64Array to work with an array buffer in Node. Here's what I've tried... var ab = new ArrayBuffer(buffer.length); var view = new Uint8Array(ab); console.log(view.length);//prints 3204 However, when I try ...

What is the best way to retrieve a particular field from a Firestore Document using JavaScript?

Within my Firestore database, I have a structure of users that looks like this: https://i.sstatic.net/jgeCq.png The rules set up for this database are as follows: match /users/{userID} { match /public { allow read: if request.auth != nu ...

Automated login feature in JQuery utilizing localStorage

I've been working on implementing an automatic login feature for users using the "Remember Me" functionality. Below is the code I have written, but unfortunately, it's not logging in users automatically: if (localStorage.getItem("username") != ...

Vitest encountered an issue fetching a local file

I am currently working on testing the retrieval of a local file. Within my project, there exists a YAML configuration file. During production, the filename may be altered as it is received via a web socket. The code functions properly in production, but ...

What is the best way to run multiple functions from an object?

My goal is to call all the functions that are contained within an object. const data = { fruits: funcA(), vegetables: funcB(), bread: funcC(), } The desired result looks like this: firstFunc(); dispatch(funcA()); dispatch(funcB()); dispatch(funcC() ...

What could be causing the Vue.js image component to malfunction?

I am having an issue. I want to create a Vue.js Component. This component displays an image, similar to the <img> tag. If you are familiar with the <img> tag, this question should be easy for you to understand. Here is the code I have: props ...

Issue with functionality of Bootstrap 4 Checkbox accordion

I am trying to achieve something similar to this example: https://getbootstrap.com/docs/4.0/components/collapse/#multiple-targets Instead of using a button, I want to use a checkbox. I want the collapse effect to occur when the checkbox is checked. < ...