Strategies for Sorting Nested Arrays in JavaScript

Here is the JSON data I have:

{
  "list": [
    {
      "deviceId": "2a-d539-4031-9bfc-4a42f2f765cf",
      "versions": [
        {
          "id": "764c20-a213-9235f4b553b3",
          "createdTime": 1590361208034,
          "files": [
            {
              "fileType": "VLAN"
            },
            {
              "fileType": "STARTUPCONFIG",
            }
          ],
          "startupRunningStatus": "OUT_OF_SYNC",
          "createdBy": "SCHEDULED"
        },
        {
          "id": "9bd33-a45a-ed2fefc46931",
          "createdTime": 1589972337717,
          "files": [
            {
              "fileType": "VLAN",
            },
            {
              "fileType": "STARTUPCONFIG",
            },
            {
              "fileType": "RUNNINGCONFIG",
            }
          ],
          "startupRunningStatus": "IN_SYNC",
          "createdBy": "SCHEDULED_FIRST_TIME"
        }
      ]
    }
  ]
}

I am looking to filter the data where "fileType": "RUNNINGCONFIG" and "fileType": "STARTUPCONFIG" are present inside the 'files' array, and only return that specific array.

For example, from the JSON above, only the second object will be returned.

I attempted to write some filter code for this purpose, but it is not functioning correctly. Can you please guide me?

let versionsData = response.data.versions;


versionsData = versionsData.filter(
                        versions => {
                            versions.files.filter(
                                m =>  {
                                    return m.fileType === "RUNNINGCONFIG"
                                }
                            )
                        }
                    );
                return versionsData;

Answer №1

Instead of using nested filters, you can leverage Array.prototype.some

const obj = {
  "list": [
    {
      "deviceId": "2a-d539-4031-9bfc-4a42f2f765cf",
      "versions": [
        {
          "id": "764c20-a213-9235f4b553b3",
          "createdTime": 1590361208034,
          "files": [
            {
              "fileType": "VLAN"
            },
            {
              "fileType": "STARTUPCONFIG",
            }
          ],
          "startupRunningStatus": "OUT_OF_SYNC",
          "createdBy": "SCHEDULED"
        },
        {
          "id": "9bd33-a45a-ed2fefc46931",
          "createdTime": 1589972337717,
          "files": [
            {
              "fileType": "VLAN",
            },
            {
              "fileType": "STARTUPCONFIG",
            },
            {
              "fileType": "RUNNINGCONFIG",
            }
          ],
          "startupRunningStatus": "IN_SYNC",
          "createdBy": "SCHEDULED_FIRST_TIME"
        }
      ]
    }
  ]
}
let versionsData = obj.list[0].versions;

versionsData = versionsData.filter(
    versions => 
        versions.files.some(
            m =>  m.fileType === "RUNNINGCONFIG"
        ) && versions.files.some(
            m => m.fileType== 'STARTUPCONFIG'
        )

);
console.log(versionsData);

Using Array.prototype.filter

const obj = {
  "list": [
    {
      "deviceId": "2a-d539-4031-9bfc-4a42f2f765cf",
      "versions": [
        {
          "id": "764c20-a213-9235f4b553b3",
          "createdTime": 1590361208034,
          "files": [
            {
              "fileType": "VLAN"
            },
            {
              "fileType": "STARTUPCONFIG",
            }
          ],
          "startupRunningStatus": "OUT_OF_SYNC",
          "createdBy": "SCHEDULED"
        },
        {
          "id": "9bd33-a45a-ed2fefc46931",
          "createdTime": 1589972337717,
          "files": [
            {
              "fileType": "VLAN",
            },
            {
              "fileType": "STARTUPCONFIG",
            },
            {
              "fileType": "RUNNINGCONFIG",
            }
          ],
          "startupRunningStatus": "IN_SYNC",
          "createdBy": "SCHEDULED_FIRST_TIME"
        }
      ]
    }
  ]
}
let versionsData = obj.list[0].versions;

versionsData = versionsData.filter( versions => {        return versions.files.filter( m => { 
     return m.fileType === "RUNNINGCONFIG" || m.fileType === "STARTUPCONFIG" }).length > 1 }
);
console.log(versionsData);

Answer №2

Using nested filters to extract specific data.

let data = {
  "list": [
    {
      "deviceId": "2a-d539-4031-9bfc-4a42f2f765cf",
      "versions": [
        {
          "id": "764c20-a213-9235f4b553b3",
          "createdTime": 1590361208034,
          "files": [
            {
              "fileType": "VLAN"
            },
            {
              "fileType": "STARTUPCONFIG",
            }
          ],
          "startupRunningStatus": "OUT_OF_SYNC",
          "createdBy": "SCHEDULED"
        },
        {
          "id": "9bd33-a45a-ed2fefc46931",
          "createdTime": 1589972337717,
          "files": [
            {
              "fileType": "VLAN",
            },
            {
              "fileType": "STARTUPCONFIG",
            },
            {
              "fileType": "RUNNINGCONFIG",
            }
          ],
          "startupRunningStatus": "IN_SYNC",
          "createdBy": "SCHEDULED_FIRST_TIME"
        }
      ]
    }
  ]
};


let versionsData = /*response.*/data.list[0].versions;

versionsData = versionsData.filter(versions => {
  return versions.files.filter(m => {
    return m.fileType == 'RUNNINGCONFIG' || m.fileType == 'STARTUPCONFIG';
  }).length == 2;
});

console.log(versionsData);

Answer №3

const information = {
  "list": [
    {
      "deviceId": "2a-d539-4031-9bfc-4a42f2f765cf",
      "versions": [
        {
          "id": "764c20-a213-9235f4b553b3",
          "createdTime": 1590361208034,
          "files": [
            {
              "fileType": "VLAN"
            },
            {
              "fileType": "STARTUPCONFIG",
            }
          ],
          "startupRunningStatus": "OUT_OF_SYNC",
          "createdBy": "SCHEDULED"
        },
        {
          "id": "9bd33-a45a-ed2fefc46931",
          "createdTime": 1589972337717,
          "files": [
            {
              "fileType": "VLAN",
            },
            {
              "fileType": "STARTUPCONFIG",
            },
            {
              "fileType": "RUNNINGCONFIG",
            }
          ],
          "startupRunningStatus": "IN_SYNC",
          "createdBy": "SCHEDULED_FIRST_TIME"
        }
      ]
    }
  ]
}

const processData = () => {
  return information.list[0].versions.reduce((result, item) => {
    const fileTypes = item.files.map(f => f.fileType);

    return fileTypes.includes('STARTUPCONFIG') && fileTypes.includes('RUNNINGCONFIG') ? 
    [...result, item] : result
  }, [])
}

console.log(processData());

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

Tips for mocking a particular http resource (URL) solely in Angular

I'm part of a team with front-end and back-end developers. At times, the front-end team needs to make REST requests to an http address or REST-resource that hasn't been implemented yet. Within ngMockE2E, I've come across the $httpBackend se ...

Obtaining the HTML content of a div element that has been retrieved through an AJAX request to a PHP script

My challenge is to fetch a dropdown menu from a server and then manipulate it using jQuery after loading. Although everything loads correctly, I am unable to interact with the dropdown items because they were dynamically added post AJAX response instead of ...

The error of 'illegal invocation' occurs when attempting to use input setCustomValidity with TypeScript

I am new to the Typescript world and currently converting one of my first React applications. I am facing an issue while trying to set custom messages on input validation using event.target.setCustomValidity. I keep getting an 'Illegal invocation&apo ...

Looking for a way to view the files uploaded in a form using ajax?

Currently, I am encountering an issue while attempting to upload a file submitted in a form using PHP. To avoid page reloading, I have incorporated JS, jQuery, and AJAX between HTML and PHP. Unfortunately, I am facing difficulties with the $_FILES variable ...

Executing a nested function as an Onclick event in an HTML document

I am currently working on a project within the Phone Gap framework where I need to transfer values from one HTML page to another. My solution involved using the code snippet below. var searchString = window.location.search.substring(1),i, val, params = s ...

In Javascript, determine the root cause of a boolean expression failing by logging the culprit

Within my JavaScript code, I have a complex predicate that comprises of multiple tests chained together against a value. I am looking for a way to log the specific location in the expression where it fails, if it does fail. Similar to how testing librarie ...

Exploring the differences between an XMLHTTP request and a string and establishing a callback mechanism

After being a silent observer for quite some time, I've finally mustered up the courage to make my first post here, so please be kind... My journey with Javascript has just begun, and although I plan on delving into jQuery eventually, for now, I am f ...

What is the best way to continuously monitor MongoDB for updates and sync them with my user interface?

Looking to continuously monitor a user's notifications in MongoDB, updating them on specific actions and displaying updates on my React frontend without reloading every time the user logs in. I am currently utilizing Node and Mongoose models for datab ...

How to run 'npm' scripts externally in package.json on Windows?

In the world of development, running arbitrary commands using npm run is a common practice. This involves adding a scripts hash to your package.json: "scripts": { "build-js": "browserify browser/main.js | uglifyjs -mc > static/bundle.js" } To exec ...

Issue: unable to establish a connection to 127.0.0.1:465 to send an email

When attempting to send smtp alert messages from my site's email account <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55363a3b2134362115383a3b263c21307b363">[email protected]</a> to the email addresses of m ...

Mastering the art of maximizing efficiency with the Jquery Chosen Plugin

Currently, I'm facing an issue with the jQuery chosen plugin due to my large datasets causing the select box to hang and slow down. Below is my implementation of the plugin: var request = $.ajax({ method: "POST", url: "ajaxRequest.php", d ...

Error in JSLint Object Detection

Currently using JSLint to scan the code below: 'use strict'; var mathService = { add: add, subtract: subtract, multiply: multiply, divide: divide, power: power, squareRoot: squareRoot }; function add(first, second) { retur ...

What is the fallback mechanism in Astro js when the cache is unavailable?

When the cache is not accessible in Next.js, the page will be server-side rendered and displayed using either the true or blocking fallback approach. I am curious about the approach taken by Astro.js in this situation. I am planning to develop a dynamic b ...

Utilizing jQuery in Wordpress to Toggle Content Visibility

Currently, my website pulls the 12 most recent posts from a specific category and displays them as links with the post thumbnail image as the link image. To see an example in action, visit What I am aiming to achieve is to enhance the functionality of my ...

Oops! The API request was denied with error code 401 - Unauthorized in React

I have been working on incorporating an API into my front-end project using React/Typescript. The documentation for the API specifies that authorization requires a key named token with a corresponding value, which should be included in the header. To stor ...

Syntax for private members in ES6 classes

I'm curious to know the most efficient way to declare private members within ES6 classes. In simpler terms, what is the best practice for implementing: function MyClass() { var privateFunction = function() { return 0; }; this.publicFuncti ...

Using Choices.js to inject live data into the select dropdown options

I am currently utilizing Choices.js for multi-select functionality and incorporating a select with a search box. Even though I am using Angular.js to populate the data, it does not appear to be functioning correctly. Is there anyone who can assist me in dy ...

Activate the parent navigation link when on sub-pages

I want to ensure that the parent navigation item is highlighted when a user is on a child page based on the URL. For example, if the user is currently viewing foo1-child and the parent is foo1, I need to apply the active class to Foo 1: http://foo.com/foo ...

After an orientation change event, the window.innerWidth property is behaving unexpectedly in Chrome iOS version 87.0.4280.77

After an orientation change event on Chrome iOS 87.0.4280.77, the window.innerWidth appears to be incorrect. Initially, the innerWidth is 414px when viewed on an iPhone. However, after changing the phone's orientation from landscape to portrait, the i ...

Unexpected event triggering

I have come across a snippet of code that allows me to retrieve URL query strings var QueryURL = function () { var query_url = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i< ...