javascript – merge json lines

Question:

There is a json like this:

{art: "1", quan: "1", sum: "1"}
{art: "2", quan: "1", sum: "1"}
{art: "1", quan: "1", sum: "1"}
{art: "12", quan: "1", sum: "1"}
{art: "1", quan: "1", sum: "1"}
{art: "12", quan: "1", sum: "1"}
{art: "1", quan: "1", sum: "1"}
{art: "11", quan: "1", sum: "1"}
{art: "1", quan: "1", sum: "1"}

Tell me how I can find repetitions by the 'art' field, remove repetitions and add the quan and sum fields.

That is, in the end it should turn out:

{art: "1", quan: "4", sum: "4"}
{art: "2", quan: "1", sum: "1"}
{art: "12", quan: "2", sum: "2"}
{art: "11", quan: "1", sum: "1"}

Code:

function filterArt(arr) {
    for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length - i; j++) {
            if (arr[i].art == arr[j].art){
                arr[i].quan = +arr[i].quan + (+arr[j].quan);
                arr[i].sum = +arr[i].sum + (+arr[j].sum);
                arr.splice(j,1);
            }
        }
    }
}

The code is not perfect. Please tell me which way to dig.

Answer:

You made a mistake when you did j < arr.length - i in the second loop: Then, in certain cases, your i element will not match the last elements of the array.

var arr = [
    {art: "1", quan: "1", sum: "1"},
    {art: "2", quan: "1", sum: "1"},
    {art: "1", quan: "1", sum: "1"},
    {art: "12", quan: "1", sum: "1"},
    {art: "1", quan: "1", sum: "1"},
    {art: "12", quan: "1", sum: "1"},
    {art: "1", quan: "1", sum: "1"},
    {art: "11", quan: "1", sum: "1"},
    {art: "1", quan: "1", sum: "1"}
];

function filterArt(arr) {
    for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
            if (arr[i].art == arr[j].art) {
                arr[i].quan = +arr[i].quan + (+arr[j].quan);
                arr[i].sum = +arr[i].sum + (+arr[j].sum);
                arr.splice(j, 1);
            }
        }
    }
    return arr;
}
console.log(filterArt(arr));
Scroll to Top