1

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Jan Tomczak
  • 13
  • 1
  • 2
  • 6

2 Answers2

1

items is an array, it doesn't have a value property. Instead, each element in it has such a property, and you can sort the array according to it:

items.sort((a, b) => b.value - a.value);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

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();
Vivek Bani
  • 3,703
  • 1
  • 9
  • 18