What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu

If the status for sorting and filtering is true, how do I proceed?

const items = [{
    name: "a1",
    id: 1,
    sort: 1,
    status: true,
    children: [{
      name: "a2",
      id: 2,
      sort: 1,
      status: true,
      children: [{
          name: "a3",
          id: 3,
          sort: 2,
          status: true,
        },
        {
          name: "a5",
          id: 4,
          sort: 1,
          status: true,
        }
      ]
    }]
  },
  {
    name: "b2",
    id: 2,
    sort: 2,
    status: true,
    children: [{
        name: "a2",
        sort: 1,
        status: false,
        id: 2,
        children: [{
          name: "a3",
          id: 3,
          sort: 1,
          status: true,
        }]
      },
      {
        name: "a4",
        id: 8,
        sort: 2,
        status: true,
      }
    ]
  }
];

console.log('items:', items)


const items = [{
    name: "a1",
    id: 1,
    sort: 1,
    status: true,
    children: [{
      name: "a2",
      id: 2,
      sort: 1,
      status: true,
      children: [{
          name: "a5",
          id: 4,
          sort: 1,
          status: true,
        },
        {
          name: "a3",
          id: 3,
          sort: 2,
          status: true,
        }
      ]
    }]
  },
  {
    name: "b2",
    id: 2,
    sort: 2,
    status: true,
    children: [{
      name: "a4",
      id: 8,
      sort: 2,
      status: true,
    }]
  }
];

Answer №1

To enhance the functionality, I suggest implementing two recursive functions:

  • The first function will filter out items with a status: false
  • The second function will sort the items based on their sort property

Both functions can be combined in any order that suits your requirements.

itemFilter

The filter function operates by iterating through a list of items. It examines each item to see if it contains children. If it does, the function initiates filtering on those children first before removing all items with status: false.

itemSorter

On the other hand, the sort function follows a similar structure. It traverses each item and verifies the presence of children. If found, it proceeds to sort the children first, followed by sorting the initial list of items passed to it.

const itemFilter = items => items
  .map(item => item.children 
    ? { ...item, children: itemFilter(item.children) }
    : item
  )
  .filter(item => item.status);
  
const itemSorter = items => items
  .map(item => item.children
    ? { ...item, children: itemSorter(item.children) }
    : item
  )
  .sort((i1, i2) => i1.sort - i2.sort);
  
  
const items=[{name:"a1",id:1,sort:1,status:true,children:[{name:"a2",id:2,sort:1,status:true,children:[{name:"a3",id:3,sort:2,status:true},{name:"a5",id:4,sort:1,status:true}]}]},{name:"b2",id:2,sort:2,status:true,children:[{name:"a2",sort:1,status:false,id:2,children:[{name:"a3",id:3,sort:1,status:true}]},{name:"a4",id:8,sort:2,status:true}]}];


console.log(
  itemSorter(itemFilter(items))
);

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

Steps for calculating total credit hours within a sublist

Within this nested array, I am looking to calculate the total sum of credit hours. The credit hours can be found at positions [2] and [5]. Is there a way to accomplish this task using a Python for loop without relying on Numpy? marks = [ [ "MR. ...

Leveraging the fromNow() method in UTC with moment.js

How can I ensure that my VueJS filter converts a given date into the fromNow() format in UTC time? fromNow(date) { return moment.utc(date).fromNow(); } The timestamp provided by my Laravel backend is already generated in UTC, but the ...

Is it possible to utilize axios in Vue while utilizing CORS in the API?

I am encountering an issue with making a GET request to a CORS enabled corona virus API using axios and Vue. I have no control over their server, and my Vue app was created with vue-cli. Interestingly, I am able to make two requests from different APIs - ...

Maximize Rotation - JavaScript Rotation

Currently tackling a Codewars challenge. The task involves finding the maximum possible result after performing a rotation on a given number. This rotation is unique in that 'n' number of digits will remain fixed after each rotation, with &apos ...

The problem with document.cookie: Functions properly on localhost but displays as empty when hosted on the web

I have been exploring various resources, but none seem to describe my unique situation. Currently, I am in the process of creating a website using ReactJS for the front-end and NodeJS with Express for the back-end. The production versions are accessible a ...

Creating an array of objects by parsing JSON using the jQuery .each() method

I am attempting to generate an array of objects by parsing a JSON file. Here is the pertinent code: //president object constructor function president(a_presName, a_presDates, a_presNick, a_presImage) { this.presName=a_presName; this.presDates=a_pr ...

The Grid within the Container is presented vertically rather than horizontally

I followed the coding style exactly as shown in a recent tutorial on YouTube, where the cards were displayed in a row. However, when I implemented it, they are appearing strangely in a column. Why is this happening? The default should be inline. Even afte ...

Is there a way to customize Material UI theme types and make adjustments to existing types using Typescript?

One way to customize the material ui theme is by extending its type and adding new properties, as shown here: For example, if we want to add an appDrawer property, it can be done like this: declare module '@material-ui/core/styles/createMuiTheme&apos ...

Choose an option from a dropdown menu and assign it to a JavaScript variable

Is it possible to store the selected option from a dropdown list as a JavaScript variable, even when new Ajax content is loaded on the page? Below is a simple form code example: <form name="searchLocations" method="POST"> <select name="l ...

Issue connecting database with error when combining TypeORM with Next.js

I am attempting to use TypeORM with the next.js framework. Here is my connection setup: const create = () => { // @ts-ignore return createConnection({ ...config }); }; export const getDatabaseConnection = async () => { conso ...

What is the best way to automatically scroll to the bottom of a modal after making a request and

I've been faced with a challenge regarding an online chat widget. My goal is to automatically scroll the widget down to display the latest message when a specific chat is opened. Despite using an async function, I encountered difficulties in achieving ...

Addressing the issue of Google Charts legends overlapping

As a newcomer to Stackoverflow and Google Charts, I am encountering an issue in one of my projects that utilizes the Google Charts API. Specifically, I am trying to display two legends on the chart but they are overlapping in the preview. Despite explorin ...

Error TS2339 occurs when attempting to migrate to TypeScript due to the absence of the 'PropTypes' property on the 'React' type

Currently in the process of converting a javascript/react project to a typescript/react/redux project. Encountering an issue with this particular file: import React from 'react'; import GoldenLayout from 'golden-layout'; import {Provi ...

Trouble with mobile compatibility for .json file content population in HTML elements script

Check out THIS amazing page where I have a series of placeholders for phone numbers in the format: 07xxxxxxxx. By simply clicking the green button "VEZI TELEFON", each placeholder in the green boxes gets replaced with a real phone number from a JSON file u ...

Enigmatic Cartography Classification

In my attempt to construct a specialized Map-like class that maps keys of one type to keys of another, I encountered a challenge. A straightforward approach would be to create a Map<keyof A, keyof B>, but this method does not verify if the member typ ...

I am facing an issue where my video file is not being recognized by Next.js when using TypeScript

In my project using next.js, typescript, and tailwindcss, I encountered an issue while creating the Masthead for my website. I wanted to set a video as the background, but for some reason, the video was not being recognized. I tried moving it to differen ...

I am in the process of creating a dropdown menu for a navbar that will appear when the cursor hovers over a specific element, complete with an arrow pointing upwards

In my current project with NextJS and Tailwind CSS, I've successfully created a dropdown menu but I'm facing an issue with positioning the arrow to point to the specific element being hovered on. In a previous version, I tried rotating a div at 4 ...

Troubles arise when trying to convert a schema using Normalizr

Is there a way to efficiently convert a JSON array containing travel expenses into a format that allows for easy retrieval of expenses by travelExpenseId and tripId? [ { "travelExpenseId":11, "tripId":2, "paymentPurpose":"some payment ...

Guide on how to capture tweets from particular Twitter profiles

I'm currently experimenting with the twitter npm package to stream tweets from specific accounts, but I'm facing some challenges. After reviewing the Twitter API documentation, I must admit that I am a bit perplexed. To fetch details about a pa ...

Ways to send user input to a function within a React component

I am currently working on implementing a simple feature where users can search posts by their tags. To achieve this, I have created the Feed.jsx component with the following code: "use client"; import { useState, useEffect } from "react&quo ...