I want the empty object filteredProducts{}
to return tech and food as key but it returns empty, and I don't know where the error is.
function sortProducts(matrix) {
//declaro las variables
const filteredProducts = {};
let techArray = [];
let foodArray = [];
//bucle para recorrer el array input
for (let i = 0; i < matrix.length; i++) {
let products = matrix[i];
//declaro las variables para asignarle los nuevos valores
let category = products.product;
let tech = category === "tech";
//condicional que agrega el valor tech al array
if (tech) {
techArray.push(products[i]);
filteredProducts.tech = techArray;
}
}
//bucle para recorrer el array input
for (let i = 0; i < matrix.length; i++) {
let products = matrix[i];
//declaro las variables para asignarle los nuevos valores
let category = products.product;
let food = category === "food";
//condicional que agrega el valor tech al array
if (food) {
foodArray.push(products[i]);
filteredProducts.food = foodArray;
}
}
//retorno los valores en el array vacio
return filteredProducts;
}
//este es el array de input
let matrix = [
[{
product: "MacBook",
price: 1019,
category: 'tech'
},
{
product: "Cheerios",
price: 5,
category: 'food'
},
],
[{
product: "Snickers",
price: 1.5,
category: 'food'
},
{
product: "Air Pods",
price: 129,
category: 'tech'
},
],
];
sortProducts(matrix);
Leaving aside the errors that you have in your code, which I have not been able to reproduce because it is an image, I propose this solution to what I think you want to obtain:
Explanation:
Inside the first
for
, which takes each array from the matrix object and returns a series of two objects, I loop back through them one by onefor
in order to get to their properties.I establish a conditional to assemble the desired output of the filteredProducts object , which must contain the two existing categories as keys, and for this I access them through
matrix[i][j].category
, which I am going to use to establish a new key in filteredProducts by writing it with this bracket syntax that May I:and as the value of the key I am going to tell it that it is an array by means of this assignment:
and so we are going to go through all the objects of all the arrays contained in the matrix and the new object is going to be created with its keys and its arrays in order, which, at the end of the cycles, we return with a return .
it is necessary to tell javascript that this key is an array the first time it tries to access it, because if the key does not exist yet it will be undefined . The rest of the cycles, if it already exists, will not overwrite it again but will skip that assignment.
You will tell us if it is what you intended to do and it works for you or not.