热门类别/库存检查器



我们在学校被要求进行这项活动,以寻找没有更多库存的类别。热门分类应该是唯一的,没有重复的分类。

const items = [
{ id: 'tltry001', name: 'soap', stocks: 14, category: 'toiletries' },
{ id: 'tltry002', name: 'shampoo', stocks: 8, category: 'toiletries' },
{ id: 'tltry003', name: 'tissues', stocks: 0, category: 'toiletries' },
{ id: 'gdgt001', name: 'phone', stocks: 0, category: 'gadgets' },
{ id: 'gdgt002', name: 'monitor', stocks: 0, category: 'gadgets' }
];

这是我到目前为止的代码。我只得到一个类别,不能显示有0只股票的第二个类别。

function findHotCategories(items) {

let ilen = items.length
for(let i = 0; i < ilen; i++){
if(items[i].stocks === 0){
let newArr = items[i].category
return [newArr]
}
}
};

// dont forget to UpVoted (:
const items = [
{ id: 'tltry001', name: 'soap', stocks: 14, category: 'toiletries' },
{ id: 'tltry002', name: 'shampoo', stocks: 8, category: 'toiletries' },
{ id: 'tltry003', name: 'tissues', stocks: 0, category: 'toiletries' },
{ id: 'gdgt001', name: 'phone', stocks: 0, category: 'gadgets' },
{ id: 'gdgt002', name: 'monitor', stocks: 0, category: 'gadgets' }
];
const emptyStocks = [];
for( let a in items ){ if( items[a].stocks < 1 ) emptyStocks.push(items[a]); }
console.log( emptyStocks );

return放入循环中,以便函数在匹配第一项的地方结束。

你应该在循环后返回

const items = [
{ id: 'tltry001', name: 'soap', stocks: 14, category: 'toiletries' },
{ id: 'tltry002', name: 'shampoo', stocks: 8, category: 'toiletries' },
{ id: 'tltry003', name: 'tissues', stocks: 0, category: 'toiletries' },
{ id: 'gdgt001', name: 'phone', stocks: 0, category: 'gadgets' },
{ id: 'gdgt002', name: 'monitor', stocks: 0, category: 'gadgets' }
];
function findHotCategories(items) {
let newArr = [];    
let ilen = items.length
for(let i = 0; i < ilen; i++){
if(items[i].stocks === 0){
newArr.push(items[i].category)
}
}
return [...new Set(newArr)];
}

console.log(findHotCategories(items));

如下:

const items = [
{ id: 'tltry001', name: 'soap', stocks: 14, category: 'toiletries' },
{ id: 'tltry002', name: 'shampoo', stocks: 8, category: 'toiletries' },
{ id: 'tltry003', name: 'tissues', stocks: 0, category: 'toiletries' },
{ id: 'gdgt001', name: 'phone', stocks: 0, category: 'gadgets' },
{ id: 'gdgt002', name: 'monitor', stocks: 0, category: 'gadgets' }
];
const totalStocks = items.reduce((acc, prev) => {
if (!acc[prev.category]) {
return { ...acc, [prev.category]: prev.stocks }
}
return { ...acc, [prev.category]: acc[prev.category] + prev.stocks }
}, {})
const emptyStocks = Object.keys(totalStocks).filter(key => totalStocks[key] === 0)
console.log(emptyStocks)

我的简短回答是使用filtermap函数

function findHotCategories(items) {
const result = items.filter(e => e.stocks === 0).map(e => e.category);
return [...new Set(result)];
}

最新更新