Utilize the filter function to refine and sort through objects

I have an array of objects structured as follows:

pages= [
   {
      "id":1,
      "name":"name1",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
   {
      "id":2,
      "name":"name2",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
   {
      "id":3,
      "name":"name3",
      "languages":[
         {
            "id":1,
            "lang":"en"
         }
      ]
   }
]

Furthermore, I have an array of selected languages (values are determined by clicking checkboxes):

selectedLanguages=['en'];

My goal is to filter the main array based on the values in selectedLanguages. I've attempted the following code:

pages.filter(page => {
    var present = false;
    page.languages.map(l => {
        if(selectedLanguages.includes(l.lang)) {
            present = true;
        }
    });
    if(present) {
        return page;
    }
})

The desired output is as follows: if selectedLanguages = ['en'], then all items from pages should be returned; if de, then only the first 2 elements should be returned.

While this code works, I'm interested in improving its efficiency. Any suggestions would be greatly appreciated. Thank you!

Answer №1

To achieve this, you can utilize a combination of Array#Filter, Array#find, and Array#includes:

let pages= [
   {
      "id":1,
      "name":"name1",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
   {
      "id":2,
      "name":"name2",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"fr"
         }
      ]
   }
]

let selectedLanguages=['fr'];

let result = pages.filter(e => e.languages.find(l => selectedLanguages.includes(l.lang)));
console.log(result);

Answer №2

Instead of using .map to create an intermediate array, a more efficient approach would be to check if any of the languages in the pages array contain a lang that matches any of the selectedLanguages:

const pages=[{"id":1,"name":"name1","languages":[{"id":1,"lang":"en"},{"id":2,"lang":"de"}]},{"id":2,"name":"name2","languages":[{"id":1,"lang":"en"},{"id":2,"lang":"de"}]}]
const selectedLanguages=['en'];
console.log(
  pages.filter(({ languages }) => (
    languages.some(({ lang }) => selectedLanguages.includes(lang))
  ))
)

Answer №3

To check for languages in the selectedLanguages array, you can utilize the filter() method along with the indexOf() method:

var pages= [
   {
      "id":1,
      "name":"name1",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
   {
      "id":2,
      "name":"name2",
      "languages":[
         {
            "id":1,
            "lang":"en"
         },
         {
            "id":2,
            "lang":"de"
         }
      ]
   },
    {
      "id":3,
      "name":"name3",
      "languages":[
         {
            "id":5,
            "lang":"us"
         },
         {
            "id":6,
            "lang":"de"
         }
      ]
   }
];

var selectedLanguages=['en'];

var res = pages.filter((page) => {
   var languageFound = page.languages.find(language => selectedLanguages.indexOf(language.lang) !== -1);
   if(languageFound){
     return page;
   }
});

console.log(res);

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

What is the best way to import a geojson file into Express.js?

I'm currently trying to read a geojson file in Node.js/express.js. The file I am working with is named "output.geojson". I want to avoid using JSON.parse and instead load it using express.js (or at least render it as JSON within this function). var o ...

AngularJS issue: Form submission does not trigger the controller function

I am currently learning AngularJS and I am experimenting with the sample code below to send my form data to the server. <!doctype html> <html lang=''> <head> <meta charset="utf-8"> <script src="../js/angular.min.v1 ...

Is there a way for me to retrieve the information within this function? It seems like it may be a promise, but I am uncertain

I need help extracting the data from doc.data and sending it to another component based on the dropdown selection. It appears that the data is in promise format, and despite trying async/await, I am struggling to access it. Can anyone guide me on how to ...

Implementing a unique sorting algorithm for an array of numbers in Angular

I need to organize an array of numbers in descending order with a custom sorting method based on a specified number, all without splitting or filtering the array. I am currently working with Angular 17 and Rxjs 7.8. For instance, if I have this array of n ...

What is the best way to have my sliding panel automatically close when I click outside of it?

I have created a sleek sliding navigation panel for my website that appears when the screen width is reduced. Although I am satisfied with how it functions currently, I would like the panel to close when the user clicks/taps outside of it. What adjustments ...

The React component fails to render on a Razor page

Looking to render a React component within a Razor page but without using a div? You can achieve this by utilizing ReactDOM.render, however my goal is to utilize it as a tag within the Razor page itself. For example, if I have a class named App, I would li ...

Converting JSON into key-value pairs using ReactJS

Here is a JSON object that I have: [ { "crime": "LARCENY-NON_VEHICLE", "count": "23217" }, { "crime": "AUTO_THEFT", "count": "13675" ...

"Looking to trigger a server click using JQuery or Javascript in your code? Here's how you can

I am facing an issue with triggering a Server-Side OnClick event on an ASP Server Button within a User Control using JavaScript or JQuery. The current methods I have tried do not produce the desired result as they do not actually simulate a user clicking t ...

What is the best way to spin a div HTML layer?

I'm trying to modify a Div layer that looks like this: ... <style type="text/css"> <!-- #newImg { position:absolute; left:180px; top:99px; width:704px; height:387px; z-index:1; background-image:url(../Pictures/rep ...

Leveraging Angular Dragula without the need for RequireJS

I'm eager to incorporate Drag and Drop functionality into my Angular project with the help of the angular-dragula module (https://github.com/bevacqua/angular-dragula). However, it appears that this module heavily relies on RequireJS. My experience wit ...

Tips for aligning an element in the center in relation to its sibling above

Help Needed with Centering Form Button https://i.sstatic.net/QhWqi.png I am struggling to center the "Send" button below the textarea in the form shown in the image. Despite trying various methods like using position absolute, relative, and custom margin ...

Tips for relocating a CSS button

I have designed two buttons using css and I am looking to align them below the title "forecast customer activity". Due to extensive styling in css, the code might appear lengthy. Requesting assistance with a solution after reviewing the following code snip ...

Using mongoose to differentiate whether an update-upsert operation is performing an insert or an update

Is the "upsert" option for updating working correctly? I attempted to upsert an object into mongodb twice with the same key, but did not receive an inserted message. Am I overlooking something? (mongodb : v2.6.3; mongoose : 3.8.15) Member.findOneAndRemov ...

Learn how to send or submit data using the Form.io form builder

I am currently working on a dynamic drag and drop form builder, and I'm struggling to figure out how to log the data from the form. Below is the component.html file where I am implementing the drag and drop form: <div> <form-builder ...

Instructions on transferring every element of a json object into a two-dimensional array, specifically when the object title corresponds (ArduinoJson)

Currently, I'm undertaking an Arduino project that involves mixing cocktails automatically. To achieve this, I've opted to store a collection of cocktail recipes in a JSON file called cocktails.json, located on an SD card. When a cocktail is sele ...

Tips for structuring an object map with flow type to ensure that each value includes a corresponding key

In an attempt to correctly type (using Flow) a helper function called createReducer for Redux, I have utilized the code from redux-immutablejs as my starting point. I am following the recommendations from the flow documentation on typing Redux reducers, b ...

Unable to show an image within the <div> element when hovering the mouse

Is it necessary to use the background style image in order to display an image on mouseover of a name? I have implemented a controller and would like the image to be replaced by text within a div tag. Below is my HTML code: <!DOCTYPE html> <html& ...

issue with bootstrap modals single firing when using remote data source

I am facing an issue with my table that contains a list of items, each item having a <select> element with different statuses. Here's how the process is supposed to work: Upon changing the status, a modal should pop up. The modal suc ...

"Implementing usort to efficiently sort multiple fields with a mix of boolean

Here is the main array structure: Array ( [0] => Array ( [active] => true [age] => 15 ) [1] => Array ( [active] => false [age] => 10 ) [3] => Array ( [active] => false ...

What is the best way to transfer an object between views in Django?

Background/Issue In my web application, I have a job that involves running a python script to log into LinkedIn. This script launches headless chromium, navigates to the LinkedIn login page, and logs in with the proper credentials. However, sometimes Link ...