0

I am trying to create a map with unique key elements from an JSON array and set the value to the khey with a total of item property, qty for each objects with the same id. There are total 5 objects in the array. The objects with id: equals to 123 should add up to 40 and objects with id: equals 456 should add up to 90 but instead id:456 adds up to 130.

I have put together a fiddle for reference https://jsfiddle.net/5jdhatq2/2/

And here is the code

   id: 123,
   qty: 20
 },
 {
   id: 456,
   qty: 30
 },
 {
   id: 123,
   qty: 20
 },
 {
   id: 456,
   qty: 30
 },
 {
   id: 456,
   qty: 30
 }
]

var priceMap = new Map();
var dataArray = [123, 456];
var qty = 0;
for (var i = 0; i < dataArray.length; i++) {
 for (var j = 0; j < data.length; j++) {
   if (dataArray[i] == data[j].id) {
     var qty = qty + data[j].qty;
     priceMap.set(dataArray[i], qty);
   }
 }
}

console.log(priceMap.get(123), priceMap.get(456))
//expected outcome -- priceMap.get(123) -> 40 and priceMap.get(456) -> 90

Cant figure out what I am doing wrong here 

2 Answers 2

2

TLDR

You need to clear qty after one loop

Answer

When execute first loop for (var i = 0; i < dataArray.length; i++)
qty is being accumulate ex-qty, I mean 40 (id=123), so you need clear qty cuz it is global variable

var data = [{
    id: 123,
    qty: 20
  },
  {
    id: 456,
    qty: 30
  },
  {
    id: 123,
    qty: 20
  },
  {
    id: 456,
    qty: 30
  },
  {
    id: 456,
    qty: 30
  }
]

var priceMap = new Map();
var dataArray = [123, 456];
var qty = 0;
for (var i = 0; i < dataArray.length; i++) {
  for (var j = 0; j < data.length; j++) {
    if (dataArray[i] == data[j].id) {
        var qty = qty + data[j].qty;
            priceMap.set(dataArray[i], qty);
    }
  }
   qty = 0;   <- here
}

console.log(priceMap.get(123), priceMap.get(456))
//expected outcome -- priceMap.get(123) -> 40 and priceMap.get(456) -> 90
Sign up to request clarification or add additional context in comments.

2 Comments

Yep..that did it. Thanks :-)
Good luck to you 👍🏻
1

You really only need to loop through the array once to create the Map. Here I've done it with a fairly straightforward reduce() but other loop methods could be used also

const data=[{id:123,qty:20},{id:456,qty:30},{id:123,qty:20},{id:456,qty:30},{id:456,qty:30}];

const pMap = data.reduce((m, {id, qty}) => m.set(id, (m.get(id) || 0) + qty), new Map)

console.log(pMap.get(123), pMap.get(456) )

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.