如何从函数返回对象



我的课程遇到了这个挑战,我一辈子都无法破解。

您将得到一个带有单个参数的函数,该函数是一个带有对象的嵌套数组。

function sortProducts (matrix) `enter code here`

阵列(矩阵)如下所示:

[
[
{ 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'},
],
];

说明:在矩阵数组中,每个嵌套数组都包含对象。每个对象代表一个产品。

函数应该在矩阵上循环,并创建一个新对象,其中包含按类别排序的产品。然后,函数应该返回这个结果对象,该对象包含已排序的产品,存储在属性技术和食品中。

结果对象应具有以下结构:

{
tech:  [ { tech product }, { tech product } ],
food:  [ { food product }, { food product } ],
};

因此,根据我的理解,第一步是在数组上循环以创建这个新对象。反对者必须按照格式(技术:"技术产品",食品:"食品产品")对产品进行分类。

我知道答案会很简单,但我一辈子都做不到。

一种方法是先使用flatMap()压平数组,然后使用reduce按类别分组。这里有一个例子:

let arr = [
[
{ 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'},
],
]
let result = arr.flatMap(i => i).reduce((c, p) => {
c[p.category] = c[p.category] || [];
c[p.category].push(p);
return c;
}, {});
console.log(result)

我不明白为什么它被称为"sortProducts";,你没有排序,只是将输入解析或转换为另一个对象。

试试这样的东西:

function sortProducts(matrix){
var result = {};
for (let i = 0; i < matrix.length; i++) {
const arr = matrix[i];

for (let j = 0; j < arr.length; j++) {
const obj = arr[j];
var newObj = { product: obj.product, price: obj.price};

// If result already has the category then just push the new object
if (result[obj.category]) {
result[obj.category].push(newObj);
continue;
}
// Otherwise add the category and add the object inside an array
// This automaticly ensures that the result.category is an array
result[obj.category] = [newObj];
}
}
return result;
}

所以解决方案比我想象的还要简单:'(

function sortProducts (matrix) {
const tech = [];
const food = [];

for (let i = 0; i < matrix.length; i++) {
const arr = matrix[i];
for (let j = 0; j < arr.length; j++) {
const product = arr[j];

if ( product.category === 'tech') {
tech.push(product);
}
else if (product.category === 'food') {
food.push(product);
}
};
};  

return {
tech: tech,
food: food,
}
}

我不知道我怎么没弄明白。希望能继续这条学习曲线。

这里有一个替代解决方案:

function sortCart(cart) {
let sortedCart = {}
cart.forEach((items) => {
items.forEach((item) => {
if (!sortedCart[item.category]) {
sortedCart[item.category] = []
}
sortedCart[item.category].push(item)
})
})
return sortedCart
}

let cart = [
[
{ 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'},
],
]
console.log(sortCart(cart))

最新更新