Best answer

Code Step filter related arrays

  • 26 January 2021
  • 5 replies
  • 141 views

Hello, 

I have related arrays coming from a GET request, in the form of product category ID and product names. 

I would like to filter products based on their category to keep only products from category ‘11’ in my example. 

I tried to play with the code step thanks to the articles from @erinoz and @TimS (thanks guys)! Unfortunately I am missing a step and there is still an error. 

Expected result should be: 

Categorie_ID: [11, 11, 11]

Product: [Lavabo, Douche, Lavabo]

Here is what I have done so far

And here is my code: 

const {
Categorie_ID,
Product,
} = inputData;

const Cat_ID_Array = Categorie_ID.split(",");
const Product_Array = Product.split(",");

const filteredCat_ID = Cat_ID_Array.filter(Categorie => Categorie.includes('11'));

console.log(data);

output = [{
filtered_Cat_ID: filteredCat_ID,
Product_Array,
}];


Thanks a lot

icon

Best answer by GetUWired 27 January 2021, 14:50

View original

This post has been closed for comments. Please create a new post if you need help or have a question about this topic.

5 replies

Userlevel 7
Badge +12

Hi @lmaillard 

 

The first thing you need to do is remove the line console.log(data) 

the variable data Is not defined anywhere which will result in the error you see. Just removing that will allow your code to run successfully and filter the categorie ids that aren’t ‘11’.

 

It does not change the Product ID array though. Give me just a sec and I will come back with a code solution for you

Userlevel 7
Badge +12

const {
  Categorie_ID,
  Product,
} = inputData;
console.log(Product);

const Cat_ID_Array = Categorie_ID.split(",");
const Product_Array = Product.split(",");

//define the new arrays
let filteredProducts = [];
let filteredCat_ID= []; 

//for each category ID, if id == 11, push id & corresponding product into new arrays
let j=0;
Cat_ID_Array.forEach(id => {
if (id==11) {
  filteredCat_ID.push(id)
  filteredProducts.push(Product_Array[j]);
}
  j++;
})

//return the filtered ids and products
return {
  "Filtered Cat ID": filteredCat_ID,
  "Filtered Products": filteredProducts
};
 

Userlevel 7
Badge +12

@lmaillard Please copy and paste the code I provided. Let me know if you need anything else!

It’s working, thanks a lot @GetUWired .

Userlevel 7
Badge +12

@lmaillard 

Happy to help!