Vinfoster0701 Vinfoster0701 - 4 months ago 11
Javascript Question

Javascript array check value and assign into the array

So, I have a PHP function that will read a csv file and then pass it to the angularJS.

Inside the csv file, there are 4 types of data

[0] => Number,
[1] => Code,
[2] => Description,
[3] => Qty


However, there is also "Area" data. The "Area" will be on "number" [2]

[0] => "",
[1] => "",
[2] => Area,
[3] => ""


This is the illustration

//Part 1
"","","Area 1",""
"No","Code","Description","QTY"
"No","Code","Description","QTY"
"No","Code","Description","QTY"
"No","Code","Description","QTY"
"No","Code","Description","QTY"
//Part 2
"","","Area 2",""
"No","Code","Description","QTY"
"No","Code","Description","QTY"
"No","Code","Description","QTY"
"No","Code","Description","QTY"
//And so on


What I want to achieve is, how can I get the area and then push it into my array by checking if [0] is empty and [2] is not null, then it is the area for the rest of array object, and once it detects same condition as before, it will assign new area for another part.

This is my array, called vm.products

for (var index = 0; index < resp.data.csv.length; index++) {
vm.products.push({
code: resp.data.csv[index][1],
qty: resp.data.csv[index][3],
//area: resp.data.csv[index].area,
description: resp.data.csv[index][2]
});
}


Thank you for any help given :)

Answer

First, you have to check whether the current entry contains the Area. If so, store it until the next Area comes by. When that happens, just replace the old Area with the new one.

While pushing the products to the array, just use the Area variable as it will always contain the correct Area.

var area = “”;
for (var index = 0; index < resp.data.csv.length; index++) {
    var current = resp.data.csv[index];
    if (current[2] != “” && (!current[0] || current[0] == "") {
        area = current[2];
    } else {
        vm.products.push({
            code: current[1],
            qty: current[3], 
            area: area,
            description: current[2]
        });
    }
}

This solution will loop only once over your array instead of multiple times when using a map first in the answer below.