I was trying to reference an object (which is inside of an array) and there is an error:
Cannot read property 'sort' of undefined
This is my code:
const items = [
{ id: 1, value:5, weight: 14 },
{ id: 2, value:8, weight: 3 },
{ id: 3, value: 10, weight: 8},
{ id: 4, value: 2, weight: 4},
];
maxWeight = 15;
function sort(){
let sort = 0;
items.value.sort((a, b) => b - a);
for(let i = 0; i < items.length; i++){
console.log(items[i].value)
sort += items[i].value;
if(sort <= maxWeight){
break;
}
}
console.log(sort);
}
sort();
What did I do wrong? Did I reference an object incorrectly?
Check this to items.sort((a, b) => b.value - a.value);
assuming you want to sort by value
key
const items = [
{ id: 1, value:5, weight: 14 },
{ id: 2, value:8, weight: 3 },
{ id: 3, value: 10, weight: 8},
{ id: 4, value: 2, weight: 4},
];
maxWeight = 15;
function sort(){
let sort = 0;
items.sort((a, b) => b.value - a.value);
//console.log(items);
for(let i = 0; i < items.length; i++){
console.log(items[i].value)
sort += items[i].value;
if(sort <= maxWeight){
break;
}
}
console.log(sort);
}
sort();