1

I want to add validation for following java script associative array.

Here is my array structure

array = [
         { id: 1, remaining_amount: 30, total: 20 },
         { id: 1, remaining_amount: 30, total: 20 },
         { id: 2, remaining_amount: 50, total: 40 }
        ]

From the above array, for id 1, remaining amount is 30 but total amount is 40

So i want to add the validation that if total amount is grater then remaining amount for particular id then it will show me message.

Any Idea?

3
  • So the remaining_amount will always be the same on all array elements with the same id? Commented Apr 3, 2018 at 7:12
  • Yes it will be same with same id Commented Apr 3, 2018 at 8:03
  • Please check answer below. Commented Apr 3, 2018 at 8:12

2 Answers 2

1

You can use reduce and filter

Use reduceto summarise the total. and use filter to get all those array that total is greater than remaining_amount

var array = [{ id: 1, remaining_amount: 30, total: 20 },{ id: 1, remaining_amount: 30, total: 20 },{ id: 2, remaining_amount: 50, total: 40 }];

var result = Object.values(array.reduce((c, v) => {
  c[v.id] = c[v.id] || {id: v.id,remaining_amount: v.remaining_amount,total: 0};
  c[v.id].total += v.total;
  return c;
}, {})).filter(o => o.remaining_amount < o.total);

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

Happy to help :)
0

You can use this code -

array.forEach(function(obj) {

   if (obj.total > obj.remaining_amount) 
     console.log(`for id ${obj.id}, remaining amount is ${obj.remaining_amount} but total amount is ${obj.total}`);
});

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.