Sort through a collection of arrays that each contain objects

Having a challenge filtering a multidimensional array with objects within the inner arrays. Despite following examples found here, I'm still unable to successfully filter my array as desired.

let arr = [ { name: 'brent', age: 123 } ];

Although I can see the filter function working when console logging, the result is always returning undefined and I can't figure out why.

let filteredData = [];
let responseData.results = [...]; //The contents of this array are below in the next block

filteredData = responseData.results.forEach((group) =>
{
    group.filter(({ customerName }) => customerName.includes(searchTerm));
});

console.log(filteredData); //returns as undefined?
let responseData.results = [
  ...
]

Answer №1

There are two common approaches to tackle this issue.

You can start by using a map:

const filteredData = responseData.results.map((group) => {
  return group.filter(({ customerName }) => customerName.includes(searchTerm));
});

Alternatively, you can opt for a shorter syntax with implicit inline return:

const filteredData = responseData.results.map((group) =>
  group.filter(({ customerName }) => customerName.includes(searchTerm))
);

Another option is utilizing reduce to eliminate non-filtered objects from responseData.

const filteredData = responseData.results.reduce((result, group) => {
  const match = group.filter(({ customerName }) =>
    customerName.includes(searchTerm)
  );
  if (match) result.push(match);
  return result;
}, []);

For further insights:

MDN - reduce()

MDN - map()

Answer №2

The issue here is a simple error in variable naming. The variable filteredData has not been updated properly. Simply rename filteredLicenses to filteredData and the problem should be resolved.

Answer №3

To effectively filter each group (sub array) and add only the filtered groups with at least one item to the resulting array, you can utilize the reduce method. On the other hand, using the map method might insert empty groups into the resulting array, which is why it's advisable to use reduce for better handling.

Check out this live demo:

const results = [
    [{
        "id": "e62d6610-04aa-4e92-806f-0449ab3becad",
        "customerName": "Immunics",
        "enduserName": "Everest",
        "productId": 4,
        "productName": "fugiat",
        "createdBy": "Keith",
        "created": "2013-10-31",
        "expires": "2011-03-03"
      },
      {
        "id": "3be2967d-cd92-488b-97e3-a8001da6d1c5",
        "customerName": "Techtrix",
        "enduserName": "Lunchpad",
        "productId": 2,
        "productName": "sit",
        "createdBy": "Odessa",
        "created": "2010-02-25",
        "expires": "2011-05-22"
      },
      {
        "id": "a67861ae-4e1b-4637-af45-096d6ed7a50f",
        "customerName": "Kaggle",
        "enduserName": "Strezzo",
        "productId": 4,
        "productName": "consequat",
        "createdBy": "Matilda",
        "created": "2010-09-05",
        "expires": "2011-08-01"
      },
      {
        "id": "182f84d5-fc27-414c-b011-0e26a9b8e688",
        "customerName": "Idealis",
        "enduserName": "Blurrybus",
...
...long snippet continues 
.as-console-wrapper {
  max-height: 100%!important;
}

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

Trouble with Google Maps API clicking on url links

I've added markers to a Google Map and I'm trying to open the specific country's PHP page when a marker is clicked, but for some reason it's not working. Below is an example of my code: <script> function initMap() { var ger ...

What steps do I need to take to ensure NextJS stores my edits in VSCode?

I have attempted various troubleshooting steps such as changing file extensions from .js to .jsx, turning on Prettier for formatting upon saving, setting it as the default formatter, reloading and restarting the editor. However, the issue with not being ...

Is it possible to convert milliseconds into the format HH:MM:SS:UU using either JavaScript or PHP?

Is there a way to convert integer milliseconds, for example 619308, into a format like HH:MM:SS:UU using JavaScript or PHP? My apologies for any language errors. ...

Transferring data from one page to another using form variables

Currently, I have an existing app at . The app is designed to function on a single page, but I have been requested to convert it into a multi-page flow. Transitioning data from one page to another has proven to be challenging for me as I am more of a hobby ...

Organize a series of <span> elements into rows and columns through the use of CSS, JavaScript, or jQuery

Task: Your challenge is to display a list of span elements in both vertical and horizontal layouts without altering the HTML structure. Input: an unknown number of span elements within a parent span like the example below: <span id="parent"> <sp ...

How can I prevent the angularFire $add(user) method from duplicating records? Is there a way to ensure that firebase records remain unique?

I need help preventing duplicate records in AngularFire when adding users to my database. How can I ensure that a user is only added once, without creating duplicates? Here is an example of the button I am using: <a class="btn btn-block btn-lg btn-suc ...

Whenever I press the button, the post request is successfully sent, and the console.log function is working perfectly within the app.post function. However, the res.send() method does not

Whenever I click on the button with the class (.hw), a POST request is successfully sent, and the console.log function works fine in the app.post. However, the res.send() method doesn't seem to reflect in the browser. I also attempted to end the respo ...

Display input checkboxes using ng-repeat based on dynamically changing conditions

My goal is to dynamically display checkboxes with labels based on a conditional flag. The label values are defined as: $scope.listA = [ { name : "Sample 1" }, { name : "Sample 2" } ]; $scope.listB = [ { name : "Result 1" } ...

The smart table's search feature seems to be malfunctioning with the table data

Having some trouble with search functionality in my "smart-table". I'm using Restangular to load data into the table successfully, but when I try to search, no data is displayed. I'm new to Angular and web development in general, so I'm a bi ...

How to fetch React route parameters on the server-side aspect

I encountered a challenge while working with ReactJS and ExpressJS. The user uploads some information on the /info route using React and axios. Then, the user receives route parameters from the server side to redirect to: axios.post('/info', Som ...

Tips for accessing and modifying local JSON data in a Chrome Extension

I am working on an extension and need to access and modify a local JSON file within the extension's directory. How can I accomplish this task? ...

Experiencing difficulties with the app.post function is leading to the error message saying "Cannot

Currently, I'm facing an issue with the functionality of "app.post" while working on building a sign-up page that allows users to input their information. This is the code snippet I've put together so far: const express = require("express"); con ...

Troubleshooting Vue.js 2 Routing Issues: Difficulty Accessing Posts Variable

My first venture into Vue.js involves working with WP REST API. Initially, all my posts are displayed perfectly. However, when I attempt to integrate Vue-router, the component responsible for showcasing all the posts, 'home-post-list', breaks do ...

Guide to assigning unique identifiers to all elements within an array using JavaScript

I have an array of objects with numeric keys that correspond to specific data values. I am attempting to restructure this object in a way that includes an 'id' field for each entry. Here is the original object: [ { "1": "data1", "5": "d ...

Steps for adding a div after a specified number

To display the following div after getting a value greater than or equal to the specified value and retrieving it through ajax: 1. How can I show the below div with the given value? .mainbox{ width:auto; height:auto; padding:20px; background:#f00; } .i ...

How can I implement a unique click handler for each individual owl carousel instance to refresh them

I'm working with multiple owl carousels that share the same class. The challenge is figuring out how to target the current slider and refresh the next one when clicked, making it the new current slider. Here's my current code snippet: $(".o ...

Exploring the process of adding arrays to highcharts using jQuery

All my coding work has been carried out on FIDDLE I have carefully monitored all the arrays: MARKET[0], MARKET[1], MARKET[2], MARKET[3], MARKET[4], MARKET[5], MARKET[6], MARKET[7]. They display correctly in alerts. However, when I attempted to incorporate ...

Is there a way to access data from a different cart template containing personalized values on Shopify?

After analyzing the values required from product.json, I realized that the current method is not efficient. The client-side ends up processing unnecessary information and every new product or option adds to the request load. Below is the script responsible ...

Performing array multiplication in Java without the use of a for loop

Imagine having two arrays of numbers with equal length. The goal is to create a third array following this pattern: c[0] = a[0] * b[0] c[1] = a[1] * b[1] ... In Matlab, one could achieve this using a loop to multiply the elements like so: for i=1:length ...

Incorporating User Input: Adding Paragraph Elements with HTML and Javascript to a Div Container

I am attempting to test my ability by creating a basic webpage. My goal is to take the text entered by the user in a textarea and add it to the page using a button. This button should generate a new paragraph element, place the user input inside of it, and ...