Reputation: 73
The Module i'm coding in node.js accepts name and price of an item, appends it to an array, then outputs the list of those items sorted in ascending price order(lowest to highest). Im having trouble with the sorting part; every time i run the module through my test code, it gives me a "TypeError: Cannot read property 'forEach' of undefined", and i cannot figure out how to fix this. Any help would be very much appreciated. Module Code:
'use-strict';
let list = [];
exports.addItem = function(name, price) {
let item = {name:name, price:price};
list.push(item);
return list;
};
exports.items = function(){
list.sort(function(a, b) {
return a - b;
})
};
And test code:
'use strict';
const inventory = require('./inventory.js');
inventory.addItem('milk', 4.00);
inventory.addItem('eggs', 1.20);
inventory.addItem('orange juice', 2.40);
inventory.items().forEach(function (item) {
console.log(`Item ${item.name} costs ${item.price}`);
});
Upvotes: 0
Views: 6114
Reputation: 249
Two things to fix here:
So the sorting function code should look something like:
exports.items = function(){
return list.sort(function(a, b) {
return a.price - b.price;
})
};
Upvotes: 3