Javascript encounters an unexpected inclusion of a split and empty array filter result

i'm attempting to sort through an array where the id values match those in another id array.

the data variable is as follows:

var data = [
    {
        "transaksi": [
            {
                "_id": "5acb747c9c2be225d995a8f1",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 50000,
                "kirim": 1,
                "pembelian": "5acb747c9c2be225d995a8f9"
            },
            {
                "_id": "5acb7a6a305ef72b7d542900",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 50000,
                "kirim": 1,
                "pembelian": "5acb7a6a305ef72b7d542908"
            }
        ],
        "_id": "5acb74239c2be225d995a8ee",
        "nama_produk": "Susu"
    },
    {
        "transaksi": [
            {
                "_id": "5acb747c9c2be225d995a8f2",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 20000,
                "kirim": 1,
                "pembelian": "5acb747c9c2be225d995a8f9"
            },
            {
                "_id": "5acb7a6a305ef72b7d542901",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 20000,
                "kirim": 1,
                "pembelian": "5acb7a6a305ef72b7d542908"
            }
        ],
        "_id": "5acb74279c2be225d995a8ef",
        "nama_produk": "Remot Tv"
    }
  ]

selected id variable:

var ids = [
"5acb747c9c2be225d995a8f1",
"5acb747c9c2be225d995a8f2"
]

filter function:

var filter = function(){
  for (id of ids){
    for (dataTransaksi of data){
        console.log(dataTransaksi.transaksi.filter(transaksi => {
        return transaksi._id == id
        }))
    }
  }
}
filter()

expected result:

[
    {
        "transaksi": [
            {
                "_id": "5acb747c9c2be225d995a8f1",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 50000,
                "kirim": 1,
                "pembelian": "5acb747c9c2be225d995a8f9"
            }
          ]
    },
    {
        "transaksi": [
            {
                "_id": "5acb747c9c2be225d995a8f2",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 20000,
                "kirim": 1,
                "pembelian": "5acb747c9c2be225d995a8f9"
            }
          ]
    }
 ]

actual result includes empty and split elements: https://i.sstatic.net/I8nWa.png

thank you.

Answer №1

To filter data using Object.assign() along with .filter(), you can follow this example:

Example:

let data = [{"transaksi": [{"_id": "5acb747c9c2be225d995a8f1", "sebelum_jumlah_sortir": 1, "harga_produk": 50000,"kirim": 1,"pembelian": "5acb747c9c2be225d995a8f9"}, { "_id": "5acb7a6a305ef72b7d542900", "sebelum_jumlah_sortir": 1,"harga_produk": 50000,"kirim": 1,"pembelian": "5acb7a6a305ef72b7d542908"}], "_id": "5acb74239c2be225d995a8ee", "nama_produk": "Susu"},{ "transaksi": [{"_id": "5acb747c9c2be225d995a8f2", "sebelum_jumlah_sortir": 1,"harga_produk": 20000, "kirim": 1,"pembelian": "5acb747c9c2be225d995a8f9"},{"_id": "5acb7a6a305ef72b7d542901","sebelum_jumlah_sortir": 1,"harga_produk": 20000,"kirim": 1, "pembelian": "5acb7a6a305ef72b7d542908"}], "_id": "5acb74279c2be225d995a8ef", "nama_produk": "Remot Tv"}],
    ids = ["5acb747c9c2be225d995a8f1", "5acb747c9c2be225d995a8f2"];

let result = data.map(
  o => Object.assign(
    {}, o, {"transaksi": o["transaksi"].filter(o => ids.includes(o["_id"]))}
  )
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Avoid adding the discovered items to the outcome set.

function filtering() {
    var finalResult = [],
        identifier, transactionData;

    for (identifier of ids) {
        for (transactionData of data){
            finalResult.push(...transactionData.transactions.filter(transaction => {
                return transaction._id == identifier
            }));
        }
    }
    return finalResult;
}

var data = [{ transactions: [{ _id: "5acb747c9c2be225d995a8f1", pre_sort_quantity: 1, product_price: 50000, sent: 1, purchase: "5acb747c9c2be225d995a8f9" }, { _id: "5acb7a6a305ef72b7d542900", pre_sort_quantity: 1, product_price: 50000, sent: 1, purchase: "5acb7a6a305ef72b7d542908" }], _id: "5acb74239c2be225d995a8ee", product_name: "Milk" }, { transactions: [{ _id: "5acb747c9c2be225d995a8f2", pre_sort_quantity: 1, product_price: 20000, sent: 1, purchase: "5acb747c9c2be225d995a8f9" }, { _id: "5acb7a6a305ef72b7d542901", pre_sort_quantity: 1, product_price: 20000, sent: 1, purchase: "5acb7a6a305ef72b7d542908" }], _id: "5acb74279c2be225d995a8ef", product_name: "TV Remote" }],
    ids = ["5acb747c9c2be225d995a8f1", "5acb747c9c2be225d995a8f2"];

console.log(filtering());
.as-console-wrapper { max-height: 100% !important; top: 0; }

A condensed version.

var data = [{ transactions: [{ _id: "5acb747c9c2be225d995a8f1", pre_sort_quantity: 1, product_price: 50000, sent: 1, purchase: "5acb747c9c2be225d995a8f9" }, { _id: "5acb7a6a305ef72b7d542900", pre_sort_quantity: 1, product_price: 50000, sent: 1, purchase: "5acb7a6a305ef72b7d542908" }], _id: "5acb74239c2be225d995a8ee", product_name: "Milk" }, { transactions: [{ _id: "5acb747c9c2be225d995a8f2", pre_sort_quantity: 1, product_price: 20000, sent: 1, purchase: "5acb747c9c2be225d995a8f9" }, { _id: "5acb7a6a305ef72b7d542901", pre_sort_quantity: 1, product_price: 20000, sent: 1, purchase: "5acb7a6a305ef72b7d542908" }], _id: "5acb74279c2be225d995a8ef", product_name: "TV Remote" }],
    ids = ["5acb747c9c2be225d995a8f1", "5acb747c9c2be225d995a8f2"],
    result = data.reduce(
        (r, { transactions }) => r.concat(transactions.filter(({ _id }) => ids.includes(_id))),
        []
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

One way to approach this problem is by using the following code snippet:

const filterData = () => {
  let filteredResults = data.filter((transaction) =>
  {
    let transactionFound = false;
    for(tr of transaction.transaksi)
    {
        //console.log(ids.indexOf(tr._id));
        if(ids.indexOf(tr._id) !== -1)
        {
            transactionFound = true;
            break;
        }
    }
    //console.log(transactionFound);
    return transactionFound;
  });

  return filteredResults;
}
let finalResult = filterData();
console.log(finalResult);

Answer №4

data.filter(d => ids.indexOf(d._id) == -1)

var data = [
    {
        "transaksi": [
            {
                "_id": "5acb747c9c2be225d995a8f1",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 50000,
                "kirim": 1,
                "pembelian": "5acb747c9c2be225d995a8f9"
            },
            {
                "_id": "5acb7a6a305ef72b7d542900",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 50000,
                "kirim": 1,
                "pembelian": "5acb7a6a305ef72b7d542908"
            }
        ],
        "_id": "5acb74239c2be225d995a8ee",
        "nama_produk": "Susu"
    },
    {
        "transaksi": [
            {
                "_id": "5acb747c9c2be225d995a8f2",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 20000,
                "kirim": 1,
                "pembelian": "5acb747c9c2be225d995a8f9"
            },
            {
                "_id": "5acb7a6a305ef72b7d542901",
                "sebelum_jumlah_sortir": 1,
                "harga_produk": 20000,
                "kirim": 1,
                "pembelian": "5acb7a6a305ef72b7d542908"
            }
        ],
        "_id": "5acb74279c2be225d995a8ef",
        "nama_produk": "Remot Tv"
    }
  ]
  
  
  
 var ids = [
"5acb747c9c2be225d995a8f1",
"5acb747c9c2be225d995a8f2"
]


let filteredData = data.filter(d => ids.indexOf(d._id) == -1)


console.log(filteredData);

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

Which is more effective for a webpage that solely calculates a formula: user input fields in DIVs or forms?

My idea is to create a webpage with initially 6 input fields, which can expand to 7, 8, 9, or 10 fields when a button is pressed. These fields will have editable preset values that will be used to calculate a final value using a formula. Should I use f ...

The method you are trying to call is not defined in Laravel

I recently developed a basic CRUD blog application with tags functionality. I have integrated tags into my pages and implemented the use of Select JS for selecting and editing tags in input fields. Now, my goal is to have the input field pre-populated wit ...

VBA: Exploring the fundamental distinctions between calling a Sub or Function with or without parentheses

Recently, I encountered an issue involving passing an Array to a Sub By Reference, but the array did not actually get modified. However, I was able to resolve this issue and now I am curious as to why it happened in the first place. Here is an example of ...

Guide to displaying or concealing the header using PHP

Once the add button is clicked, the text should be hidden and the form should be displayed. Check out my code below: <h2 style="font-size: 2em; margin-bottom: 0.75em; margin-left: -1%;">Specify Co-Owners for self occupied property</h2> <div ...

Using a synchronous JavaScript AJAX function results in an empty object being returned

After conducting some research, I was unable to locate a fitting example for the current scenario. Below is the JavaScript code that I have: function retrieveGraphData(graph) { "use strict"; $.ajax({ url: 'server/ExtractTelemetry.php& ...

Ways to specify a setter for a current object property in JavaScript

Looking to define a setter for an existing object property in JavaScript ES6? Currently, the value is directly assigned as true, but I'm interested in achieving the same using a setter. Here's a snippet of HTML: <form #Form="ngForm" novalida ...

Is it necessary to use callbacks when using mongoose's findbyid with express to retrieve an object from the database? Are callbacks still important in modern JavaScript frameworks?

I'm currently exploring the express local library tutorial on MDN docs and wanted to try out returning an object without relying on a callback method. When I provide the request object parameter for the id to the findById mongoose method like this va ...

Tips for dynamically populating JSON data using a dropdown selection?

I am currently exploring HTML forms as a new web developer. I have been experimenting with displaying JSON data in a div based on a selection from a dropdown menu using jQuery in Chrome. However, my code does not seem to be functioning properly. Even tho ...

Parsing JSON multiple times to extract data on the top 10 games from Twitch's API

Hey there! I have a little coding challenge for you. The current code below is only fetching the first channel from the JSON. My goal is to fetch all the streams and display them in a grid format with three streams per row. Can you help me achieve this? (B ...

Using JavaScript with namespaces in C#

I am currently trying to explore AJAX and web services through self-teaching using C# and JavaScript. After doing some research on Google, it seems like I might be facing a namespace problem. Here is the snippet of my code: using System; using System.Col ...

Is there a specific regular expression that can be used for validating Credit Card Expiry dates in Javascript/Ang

I am currently working on a textfield where users can enter their credit card expiry date in the format mm/yy. To ensure the validity of this input, I have implemented JavaScript validation using regular expressions. Here is an example of what I have tried ...

Is there a method to bypass the need for app.get() for each static file in express?

As I delve into using express.js, I'm faced with the task of serving numerous static files from my server - whether it's a .css, .jpg, .svg, .js, or any other file type. Is there a way to accomplish this without having to manually use app.get() f ...

Struggling to make antd compatible with my create-react-app project

Exploring ant.design with create-react-app piqued my interest, so I decided to follow the steps outlined in the antd documentation. https://ant.design/docs/react/use-with-create-react-app npx create-react-app antd-demo npm add antd Within the app.js fil ...

Steps for "submitting" a portion of a form with jQuery

I have a form that resembles a spreadsheet layout. My goal is to submit specific fields from a row to the server using jQuery Ajax whenever the user navigates away from that row. The challenge arises because the page consists of one large form, making it n ...

Tips on searching for either of two items with mongoose's findOne method

In the process of setting up a login system using mongoose for data storage, I am facing a challenge. How can I check if a new user signing up does not have the same email or username as an existing user in the database? Essentially, I need to find out if ...

Vue 3 - Using Emit Functionality in a Reusable and Composable File

I'm trying to utilize the emit function in my file called useGoo.ts import Swal from "sweetalert2/dist/sweetalert2.js"; export default function useModal() { const { emit } = getCurrentInstance(); function myId() { emit('id&ap ...

Angular UI-Router will initialize the controller only when the route is activated

Suppose I have two pages called cloud and settings. Here is the code setup: var routerApp = angular.module('APP', ['ui.router']); routerApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) { $locationProvide ...

Utilizing Selenium JavaScript to insert a cookie into a request

Trying to add a cookie to the request in Selenium using JavaScript. I followed the documentation at this link, but my code snippet doesn't seem to pass any cookies to the PHP script below on the server. Here is the client-side JavaScript code: var w ...

When using jQuery, the value of an input type text field remains constant despite any alerts

My issue involves an input text used to check if the corrected values are being displayed in an alert. However, when I modify a value in the form and check if the updated value appears in the alert box, it still shows the old value. Below is the relevant ...

Issues arise with the Node EJS module due to the malfunction of the include

Struggling with incorporating HTML snippets into my index.html, even after reviewing the EJS documentation. Directory Structure: project -public --assets ---css ---images ---js --Index ---index.html + index.css and index.js --someOtherPageFolder -views - ...