1

I have an array of objects, each object contains 2 properties, month & count. count has a default value of 0. I have a another array of object which I am pulling from a json file with different count values. I am trying to replace the count value from the 2nd array to the 1st.

eg

array1[
  { 
    month:1,
    count:0
  },
  { 
    month:2,
    count:0
  },
  { 
    month:3,
    count:0
  }
  { 
    month:4,
    count:0
  }
  etc...
]

array2[
  { 
    month:1,
    count:5
  },
  { 
    month:2,
    count:3
  },
  { 
    month:3,
    count:9
  }
  { 
    month:5,
    count:4
  }
  etc...
]

My problem is that my 2nd array is shorter as there are some months missing (due to no values for them in db) in this case I would like to skip and go to the next object. so the end result would look like this,

array1[
  { 
    month:1,
    count:5
  },
  { 
    month:2,
    count:3
  },
  { 
    month:3,
    count:9
  },
  { 
    month:4,
    count:0
  }
  { 
    month:5,
    count:4
  }
  etc...
]

my code so far

var array1 = [];

for (var i = 1; i <= 12; i++) {
  array1.push({
    month: i,
    count: 0
  })
}


$.getJSON(url, function (data) {
  for (var i = 0; i < data.length; i++) {
    if (array1[i].month == data[i].month) { //work until month 4
        array1[i].count = data[i].count 
    }
});

console.log(array1);

2 Answers 2

1

If you have always the months of a year in your array, then you can use the month as index for the original array and update if necessary.

for (var i = 0; i < data.length; i++) {
    array1[data[i].month - 1].count = data[i].count;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Result will be in the first array:

function mergeArrays(arr1, arr2) {
    arr1.forEach(function(item1) {
        var item2 = arr2.find(function (item2) {
            return item2.month === item1.month;
        });
        if (item2) {
            Object.assign(item1, item2);
        }
    })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.