Jan Tomczak
Jan Tomczak

Reputation: 13

Cannot read property 'sort' of undefined

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?

Upvotes: 1

Views: 3661

Answers (2)

Mureinik
Mureinik

Reputation: 311883

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);

Upvotes: 1

Rajdeep D
Rajdeep D

Reputation: 3920

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();

Upvotes: 0

Related Questions