Using JavaScript, implement the array.filter method on a JSON array to retrieve the entire array if a specific property matches a given

Help needed with filtering an array:

In the user_array, there are arrays that need to be compared to see if the header_info.sap_number matches any value in the valid_sap_number array.

If a property value matches anything in the valid_sap_number array, the array and its parent array will be retained, while all other arrays that do not match any value from the valid_sap_number array will be removed. Refer to the example below for clarification.

Example array:

var valid_sap_number = ['1', '2']
var user_array = 
[{
  "name": "User1",
  "header_info": [{ "sap_number": "1" }],
  "footer_info": [{ "site": "ABC" }]
}],
[{
  "name": "User2",
  "header_info": [{ "sap_number": "2" }],
  "footer_info": [{ "site": "ABCD" }]
}],
[{
  "name": "User3",
  "header_info": [{ "sap_number": "3" }],
  "footer_info": [{ "site": "ABC" }]
}];

/* Filter code */

 const result = user_array.filter(user => function(a,b){        
            for(i = 0; i < valid_sap_number.length; i++)
            {
                if(b.header_info[0].sap_number == valid_sap_number[i]){
                    return true;     
                }
            }
        });

    console.log(result); 

Expected output:

result = [{
      "name": "User1",
      "header_info": [{ "sap_number": "1" }],
      "footer_info": [{ "site": "ABC" }]
    }],
    [{
      "name": "User2",
      "header_info": [{ "sap_number": "2" }],
      "footer_info": [{ "site": "ABCD" }]
    }];

Answer №1

To determine if the current item matches any of the values in the list, you can utilize the array's includes function within the filter function.

const result = user_array.filter(user => { 
  return valid_sap_number.includes(user[0].header_info[0].sap_number);
  });

Answer №2

After reviewing your feedback, it appears that there is an opportunity to enhance the structure of the JSON data. The current format may be misleading and not entirely suitable for your needs.

Suggested Proposal:

user_array = [
   {
         "name" : "User1",
         "header_info": {
            "sap_number": 1,
            //... other properties of header_info
         },
         "footer_info" : {
             "site" : "ABC",
             //... other properties of footer_info
         }
   },


{
         "name" : "User2",
         "header_info": {
            "sap_number": 2,
            //... other properties of header_info
         },
         "footer_info" : {
             "site" : "ABCE",
             //... other properties of footer_info
         }
   }

] 

Furthermore, you can create a filter using:

user_array.filter( user => valid_sap_number.includes(user.header_info.sap_number));

Answer №3

Initially, it seems that your user_array is not formatted correctly as an array.

In this scenario, you can utilize the .filter() method to resolve the issue.

Please refer to the code snippet below for a solution:

var valid_sap_number = ['1','2']
var user_array = [
[{
  "name":"User1",
  "header_info": [{ "sap_number":"1" }],
  "footer_info": [{ "site":"ABC" }]
}],
[{
  "name": "User2",
  "header_info": [{ "sap_number": "2" }],
  "footer_info": [{ "site": "ABCD" }]
}],
[{
  "name": "User3",
  "header_info": [{ "sap_number":"3" }],
  "footer_info": [{ "site":"ABC" }]
}]
];

const result = user_array.filter(a => valid_sap_number.includes(a[0].header_info[0].sap_number))

Answer №4

for (const person of user_array) {
    let output = [];
    const employeeID = person.header_info[0].employee_id;
    for (const validID of valid_employee_ids) {
        if (validID == employeeID) {
            output.push(person);
        }
    }
}
user_array = output;

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

Can someone assist me in retrieving the information stored within an object?

I'm currently working on a Discord bot and I am in need of the user ID, specifically 'xxx', but I'm unsure of how to retrieve it. Here is what I have tried so far: n.mentions.users.User. -- n.mentions.users.User() This is what my code ...

Unable to retrieve information from a child component in React

So, this component acts as the main container class TaskList extends React.Component { state = { task: '', } handleTaskClick = () => { taskArray.push({id: idCount, text: this.state.task, completed: false}) idCount++ this. ...

Tips for clicking a .class a random number of times:

Could someone help me figure out how to click a random number of times on the element with class name .CLASS when a key is pressed? I think I need to incorporate the Math.floor(Math.random()) function, but I'm not sure how to do it in my existing code ...

Executing a function a specific number of times in Jquery

I have a query regarding JQuery related to randomly placing divs on a webpage. The issue I'm facing is that it currently does this indefinitely. Is there a way to make it run for a specific duration and then stop? $(document).ready(function () { ...

MUI's Checkbox with Radio Button feature functionality

In my project, I am looking to implement a Checkbox with radio button behavior inside an Accordion component. The challenge here is that only one item should be selected at a time. If one item is checked, it should automatically uncheck the previously sele ...

Modify section background color for every iteration in an image carousel

Is it possible to dynamically change the background color of the cd-hero section each time a new image is loaded in a simple slider on the home page? Can this be achieved by storing predefined colors in an array so that different images trigger different b ...

When sending a single apostrophe as a parameter in an AJAX post request, it will result in an error

JavaScript Code: var name = jQuery("#name1").val(); jQuery.ajax({ url: siteUrl + 'search/ind', type: 'POST', data: { name: name, }, success: function(data) { jQuery('#input').val(''); } } ...

jQuery automatic slider for seamless transitions

I am in need of assistance with the coding for a website I'm currently constructing at www.diveintodesign.co.uk/ChrisMcCrone/index.html The coding being used is sourced from http://jquery.malsup.com/cycle/ The central large image functions as a slid ...

Utilizing Angular.JS to sort items based on the chosen option in a select dropdown menu

I am utilizing the WP API to display a list of posts on a page from a JSON file. I have successfully implemented filtering through an input field named searchrecipe, which allows me to search for post titles. However, I am facing a challenge with filterin ...

What techniques can I use to adjust the size of an image through zooming in and out?

In my custom gallery component, the crucial code section looks like this: <Gallery> <Header> <img src={galleryIcon} alt='Galley icon' /> <h1>My Gallery</h1> </Header> ...

The double click functionality does not seem to be functioning within the Backbone View

I am trying to detect double click event within a Backbone view var HomePage = Backbone.View.extend({ initialize: function(){ this.render(); }, render: function(){ var template = _.template($('#app1').html()); ...

Tick the checkbox to indicate that I want to insert an image in the adjacent column for the same row

Every time I click on the checkbox, an image should appear in the adjacent column for that specific row. Despite using the addClass() method and targeting the td, the image is appearing in all rows instead of just the selected one. Could somebody help me ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

Whenever the user hits the "Enter" key, a new element will be generated and added to the bottom of an existing element

I am in need of creating a new element at the end of another element. For instance, let's say I have this element: <div id="elmtobetrig">Element that should be followed by another element when the user hits enter after this text. <! ...

Troubleshooting issues with static serving in Express.js

I'm facing an issue while trying to apply a bootstrap theme to a file created using Jade. The error message indicates that it cannot GET the file. Main JavaScript code snippet: const express = require('express'); const app = express(); ap ...

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...

What is the best way to update my component when the selected value is changed?

Currently, I am facing an issue with my map component. It plots polyline data based on the option selected from the select menu component. The problem arises when I change the value in the select menu and click the play button for the animation. Instead of ...

Is it possible to dynamically create input fields in AngularJS by clicking a button?

I'm currently working on a project that involves adding an input field and a button each time a user clicks on the button. Is there a way to retrieve the text from the input field when the new button, which is displayed alongside the input field, is ...

Exploring the concept of multiple inheritance using ES6 classes

My research on this topic has been primarily focused on BabelJS and MDN. However, I acknowledge that there may be more information out there regarding the ES6 Spec that I have not yet explored. I am curious about whether ES6 supports multiple inheritance ...

Error handling in AngularJS and Firebase Promises

I am currently following a tutorial on thinkster.io and encountering some issues. The tutorial uses a deprecated SimpleLogin, so I have made the necessary code changes. However, I keep running into an error that says: TypeError: Cannot read property &apo ...