up_brn
up_brn

Reputation: 7

Return wrong array when only one data in JSON

I have passed JSON from the server-side to the client-side. I have created a function to return the latest rate and currency_id. It workes for some but not workes for some.

When I use my function for product_id 1 and 2 workes well. It returns the correct array. But this not workes for product_id 3 and 4. It returns an empty array. I have mentioned the used function below.

JS function:

COMNAME.prepEdit = function (product_id) {
const currencyIds = [];
const result = [];

const sortData = COMNAME.newCurrency
    .filter((item) => item.product_id === product_id)
    .sort((item1, item2) => item1.id - item2.id);


for (let i = sortData.length - 1; i > 0; i--) {
    const item = sortData[i];

    if(!currencyIds.includes(item.currency_id)) {
        currencyIds.push(item.currency_id)
        result.unshift(item);
    }
}

return result;
}

Please help me to find my fault here. Thank you.

Upvotes: 0

Views: 46

Answers (1)

James
James

Reputation: 351

I'm not too sure what you are trying to do but, shouldn't your for loop be something like this :

for (let i = sortData.length - 1; i >= 0; i--) { Shouldn't it be i>=0 since you also want the first index?

Upvotes: 2

Related Questions