What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and then add the matched products to an array associated with that category.

The main objective is to link the category with the product_category field.

Below are the details of the arrays:

Products

[
    {
        "id": 1,
        "product_title": "Product 1",
        "product_size": null,
        "product_author": 5,
        "description": "Test Description",
        "product_category": "Shirts,Pents,Salwar",
        "createdAt": "2020-02-08T11:42:15.000Z",
        "updatedAt": "2020-02-08T11:42:15.000Z"
    },
    {
        "id": 4,
        "product_title": "Product 2",
        "product_size": null,
        "product_author": 5,
        "description": "Test Description",
        "product_category": "Pents,Salwar",
        "createdAt": "2020-02-08T11:42:15.000Z",
        "updatedAt": "2020-02-10T07:08:23.000Z"
    }
]

Categories

[
    {
        "id": 1,
        "category_name": "Shirts",
        "createdAt": "2020-02-08T04:59:59.000Z",
        "updatedAt": "2020-02-10T06:50:05.000Z"
    },
    {
        "id": 9,
        "category_name": "Pents",
        "createdAt": "2020-02-08T04:59:59.000Z",
        "updatedAt": "2020-02-10T06:50:05.000Z"
    }
]

Here is the code snippet that I attempted but it's not functioning as expected:

    this.categories.forEach(cat => {
      this.products.filter(prod => {
        if (prod.product_category.split(',').indexOf(cat.category_name) !== -1) {
          this.categories.push(prod);
        }
      });
    });

I would greatly appreciate any guidance or solution to resolve this issue.

Answer №1

If you want to enhance the categories array, you can utilize the .map() method. By doing so, a new products property will be added to each category object. This property will contain only the products that match the category name.

const categoriesWithProducts = categories.map(cat => {
  return {
    ...cat,
    products: products.filter(prod => {
      return prod.product_category.split(',').includes(cat.category_name);
    })
  };
});
``

Answer №2

In order to categorize products, one effective method is to create a new array where items are grouped based on specific categories:

var products = [
    {
        "id": 1,
        "product_title": "Product 1",
        "product_size": null,
        "product_author": 5,
        "description": "Test Description",
        "product_category": "Shirts,Pents,Salwar",
        "createdAt": "2020-02-08T11:42:15.000Z",
        "updatedAt": "2020-02-08T11:42:15.000Z"
    },
    {
        "id": 4,
        "product_title": "Product 2",
        "product_size": null,
        "product_author": 5,
        "description": "Test Description",
        "product_category": "Pents,Salwar",
        "createdAt": "2020-02-08T11:42:15.000Z",
        "updatedAt": "2020-02-10T07:08:23.000Z"
    }
];

var categories = [
    {
        "id": 1,
        "category_name": "Shirts",
        "createdAt": "2020-02-08T04:59:59.000Z",
        "updatedAt": "2020-02-10T06:50:05.000Z"
    },
    {
        "id": 9,
        "category_name": "Pents",
        "createdAt": "2020-02-08T04:59:59.000Z",
        "updatedAt": "2020-02-10T06:50:05.000Z"
    }
]
var productCategories = [];
categories.forEach((cat)=> {
var productCategory = {};
productCategory.category = cat;
productCategory.products = [];
products.forEach(prod => { 
        if (prod.product_category.indexOf(cat.category_name) !== -1) {
          productCategory.products.push(prod);
        }
      });

productCategories.push(productCategory);
console.log(productCategories);
});

Answer №3

To achieve the same result without using filter(), you can opt for a different approach by combining forEach() with includes() and Object.assign():

var items = [
    {
        "id": 1,
        "title": "Item 1",
        "size": null,
        "author": 5,
        "description": "Test Description",
        "category": "Books,Pens,Markers",
        "createdAt": "2020-02-08T11:42:15.000Z",
        "updatedAt": "2020-02-08T11:42:15.000Z"
    },
    {
        "id": 4,
        "title": "Item 2",
        "size": null,
        "author": 5,
        "description": "Another Test Description",
        "category": "Pens,Notebooks",
        "createdAt": "2020-02-08T11:42:15.000Z",
        "updatedAt": "2020-02-10T07:08:23.000Z"
    }
];
var categories = [
    {
        "id": 1,
        "name": "Books",
        "createdAt": "2020-02-08T04:59:59.000Z",
        "updatedAt": "2020-02-10T06:50:05.000Z"
    },
    {
        "id": 9,
        "name": "Pens",
        "createdAt": "2020-02-08T04:59:59.000Z",
        "updatedAt": "2020-02-10T06:50:05.000Z"
    }
]

categories.forEach((cat,i) => {
  items.forEach(item => {
    if (item.category.split(',').includes(cat.name)) {
      Object.assign(categories[i], item);
    }
  });
});
console.log(categories);

Answer №4

To efficiently sort through product categories based on their names, you can utilize the Array#filter method along with Array#some.

let products = [{"id":1,"product_title":"Product 1","product_size":null,"product_author":5,"description":"Test Description","product_category":"Shirts,Pents,Salwar","createdAt":"2020-02-08T11:42:15.000Z","updatedAt":"2020-02-08T11:42:15.000Z"},{"id":4,"product_title":"Product 2","product_size":null,"product_author:5,"description":"Test Description","product_category":"Pents,Salwar","createdAt":"2020-02-08T11:42:15.000Z","updatedAt":"2020-02-10T07:08:23.000Z"}]

let catagories = [{"id":1,"category_name":"Shirts","createdAt":"2020-02-08T04:59:59.000Z","updatedAt":"2020-02-10T06:50:05.000Z"},{"id":9,"category_name":"Pents","createdAt":"2020-02-08T04:59:59.000Z","updatedAt":"2020-02-10T06:50:05.000Z"}]

let catagoryNames = new Set(catagories.map(e => e.category_name));

let filtered = [...products].filter(e => e.product_category.split(',').some(cat => catagoryNames.has(cat)));
console.log(filtered)

Answer №5

Give this a try

categories.forEach(function(c){
    c.products=products.filter(function(p){
        var reg=new RegExp(c.category_name,'gi');
        return reg.test(p.product_category)
    })

})

A different approach without using Regex

categories.forEach(function(c){
    c.products=products.filter(function(p){

        return (p.product_category.split(',').indexOf(c.category_name)!==-1)
    })

})

You'll find the products within each category

Check out the Fiddle here

Answer №6

Check out this code snippet for a potential solution:

productList = [
    {
        "id": 1,
        "product_title": "Product 1",
        "product_size": null,
        "product_author": 5,
        "description": "Test Description",
        "product_category": "Shirts,Pents,Salwar",
        "createdAt": "2020-02-08T11:42:15.000Z",
        "updatedAt": "2020-02-08T11:42:15.000Z"
    },
    {
        "id": 4,
        "product_title": "Product 2",
        "product_size": null,
        "product_author": 5,
        "description": "Test Description",
        "product_category": "Pents,Salwar",
        "createdAt": "2020-02-08T11:42:15.000Z",
        "updatedAt": "2020-02-10T07:08:23.000Z"
    }
]
  
categoryList = [
    {
        "id": 1,
        "category_name": "Shirts",
        "createdAt": "2020-02-08T04:59:59.000Z",
        "updatedAt": "2020-02-10T06:50:05.000Z",
    },
    {
        "id": 9,
        "category_name": "Pents",
        "createdAt": "2020-02-08T04:59:59.000Z",
        "updatedAt": "2020-02-10T06:50:05.000Z",
    }
]

categoryList.forEach(cat => {
     cat['products'] = []
      productList.filter(prod => {
        if (prod.product_category.split(',').indexOf(cat.category_name) !== -1) {
         cat['products'].push(prod);
        }
      });
});
console.log(categoryList)

Answer №7

To efficiently iterate through all categories and then navigate through each product within those categories, you can follow this process: for every product, verify if the category name is listed and if it is, add the product to that category's products list.

    this.categories.forEach(category => {
      category.products = [];

      this.products.forEach(product => {
        if (product.product_category.split(',').indexOf(category.category_name) !== -1) {
          category.products.push(product);
        }
      });
    });

It is important to note that I made a switch from using filter to utilizing forEach in this implementation.

Answer №8

        const items = [
            {
                "id": 1,
                "item_title": "Item 1",
                "item_size": null,
                "item_author": 5,
                "description": "Test Description",
                "item_category": "Shirts,Pents,Salwar",
                "createdAt": "2020-02-08T11:42:15.000Z",
                "updatedAt": "2020-02-08T11:42:15.000Z"
            },
            {
                "id": 4,
                "item_title": "Item 2",
                "item_size": null,
                "item_author": 5,
                "description": "Test Description",
                "item_category": "Pents,Salwar",
                "createdAt": "2020-02-08T11:42:15.000Z",
                "updatedAt": "2020-02-10T07:08:23.000Z"
            }
        ];
        
        const categories = [
            {
                "id": 1,
                "category_name": "Shirts",
                "createdAt": "2020-02-08T04:59:59.000Z",
                "updatedAt": "2020-02-10T06:50:05.000Z"
            },
            {
                "id": 9,
                "category_name": "Pents",
                "createdAt": "2020-02-08T04:59:59.000Z",
                "updatedAt": "2020-02-10T06:50:05.000Z"
            }
        ];
        
     



         const matchedItems = [];
            items.map(it=>{
              const isCategoryMatched = categories.some(c=>{
                  return   it.item_category.includes(c.category_name)
              });
              if(isCategoryMatched ){
                 matchedItems.push(it);
              }
            })
        //if you want to push the matched items into categories
            categories.push(...matchedItems)
    
    console.log('matchedItems',matchedItems);
    console.log('categories',categories);

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

Just encountered an issue stating "PrismaClient cannot run in the browser" while working with [Next.js]

My initial plan was to log all the IDs of news in my database using console. However, when I executed the code, an error occurred as shown in this image. What is the best way to address and resolve this issue? https://i.stack.imgur.com/ci8G1.png ...

A method for combining multiple arrays into a single array within a For loop

I am trying to combine multiple arrays of objects into a single array. Here is an example with a transaction array that contains two different arrays: transaction: 0:(3) [{…}, {…}, {…}] 1:(2) [{…}, {…}] I would like the combined result to loo ...

What could be causing my button to not capture the value of this input text field?

After clicking the button, I am trying to log the value of the input text field in the console. However, it just shows up as blank. Despite checking my code multiple times, I can't seem to figure out why. Any insights would be greatly appreciated! &l ...

I require assistance in understanding how to successfully implement ParseINT with (row.find)

enter image description hereHow To Utilize ParseINT Using row.find(). I Attempted This Code But It Doesn't Work. This is My Code : function update_qty() { var row2 = $(this).parents('.item-row'); var price2 = row2.find(parseInt($ ...

Transforming intricate JSON data into a structured table format

I'm struggling to transform the nested JSON data into an HTML table, but I keep encountering an error. I'm uncertain about where I may have made a mistake. Could it be related to how I am trying to access the array within the object? Here' ...

Utilize TypeScript to access scope within a directive

Is there a way to access the controller's scope properties using my custom TypeScript directive? For example, in this snippet below, I am trying to retrieve and log scope.message: /// <reference path="typings/angularjs/angular.d.ts" ...

Differences between JSX and creating instances of component classes

Could someone please clarify the distinction between the following two statements? let instance1 = new CustomComponent(); and let instance2 = <CustomComponent /> When checking in the Chrome debugger, I see the following: for instance1 CustomComp ...

What is the best method for streaming files from Java to the browser while preventing the user from downloading and saving the file?

I'm new to this and feeling a bit lost. Here's the situation: I have a web app (built with JavaScript/Reactjs) and a backend (Java using Liferay API) The server contains files (File A, B, C, etc.) of various types: pdf, excel, audio, txt, etc. ...

BufferGeometry's Vertices

Since version 125, the use of THREE.Geometry has been deprecated. As we update our code base, we are encountering errors that are proving difficult to resolve. Our current task involves creating a sphere and applying a raycaster on it to determine the int ...

Tips for incorporating side effects into an observable property?

I am relatively new to Mobx and I need to automatically call a function when this observable array is updated. The observable array: @observable Todos = [] I have many functions to manage this array (addTodo, removeTodo, ...) and I would like to avoid ...

Exploring Data in a Tree View Format on a PHP Website

Looking for advice on displaying categories and corresponding subcategories on the left side of my website (built using Php and Javascript). I would like the tree to be movable, similar to the functionality featured on this link: Any suggestions on how I ...

Tips for implementing validation in template-driven form using Ionic 3

How can I validate a mobile number in an Ionic 3 application? I am using ngModel, but I'm looking for an example to help me with the validation process. Can anyone provide guidance on how to do this? <ion-list> <ion-item margin ...

A guide on implementing array properties in Vue 3

Currently learning the fundamentals, I have an array set up in the parent component (App.vue) data() { return { fruits: [ "apple", "pear", "cherry" ], }; }, I'm aiming to have three instances of the s ...

Using jquery and Ajax to extract data from nested JSON structures

Need help with modifying a code snippet for parsing nested JSON format [ { "name":"Barot Bellingham", "shortname":"Barot_Bellingham", "reknown":"Royal Academy of Painting and Sculpture", "bio":"Barot has just finished his final year at T ...

Having trouble personalizing the background color according to the ItemName in angular2-multiselect-dropdown

Is it possible to customize the background color in angular2-multiselect-dropdown based on the tags label? I want the background color to be determined by the tags label. The npm package provides no description regarding this feature here https://i.ssta ...

Tips for deleting multiple uploaded images from an array using Vue.Js and updating the UI accordingly

I am currently utilizing VueJs to upload multiple images. I am saving their respective base64 values in an Array to store them in the database. I have also added a remove feature, so when the user clicks on the remove button, it finds the index of that ele ...

The practice of following the UpperCamelCase convention post object transformation

I encountered a situation where I have an object that returned the result from an RxJs subscribe method: result: any { message: null role: Object success: true } To better manage this object in TypeScript, I decided to convert it to a type ca ...

Unable to stop submission as a result of ajax verification

As someone new to java and jquery, I am facing a challenge with the code below: $(document).ready(function() { //Prevent SUBMIT if Session setting = On (Ajax) $('#formID').submit(function(e) { var prevent = false; $.ajax({ type: ...

Creating numerous Facebook posts using jQuery technology

I am currently facing a challenge when attempting to publish multiple facebook posts on a webpage using jQuery. Although I have managed to successfully post the first facebook post, I am encountering difficulties when trying to post another one. What coul ...

Issue with saving date values accurately in Nestjs/Prisma

After logging the response body before saving it to the database, I noticed that the shape is correct. Here's what it looks like: //console.log response body CreateOpenHourDto { day: 'WEDNESDAY', startTime: 1663858800000, endTime: 16638786 ...