Pavan k
Pavan k

Reputation: 11

how to filter and create an response in javascript

I am trying to maap and filter the key and value

  AvailblePointsToBuy = 100;
  lifePriority = { "cloth":1,"bike":2,"cycle":3 }
  availbility = {"cycle":40,"car":80,"cloth":10,"bike":50 }

i need to create one response based on the "lifePriority" priority and total point should not less than AvailblePointsToBuy.

output be like :    { "cloth":10,"bike":50 ,"cycle":40,}    based on the lifePriority need to sort with total points not to excude 100 points.  

Upvotes: 0

Views: 57

Answers (1)

Nitheesh
Nitheesh

Reputation: 20006

Logic

  • Loop through lifePriority.
  • Start fom the priority value 1. (OR minimum in list)
  • Find the item from lifePriority with the required priority and its matching value from availbility.
  • Add the key to the output, with value minimum of the product vailability or the total availability.
  • Decrease the total availabiity as minimum of the product vailability or zero.

AvailblePointsToBuy = 100;
const lifePriority = { "cloth": 1, "bike": 2, "cycle": 3 };
const availbility = { "cycle": 40, "car": 80, "cloth": 10, "bike": 50 };  
const output = {};
let priority = 1;
Object.keys(lifePriority).forEach((key) => {
  if(lifePriority[key] === priority) {
    output[key] = AvailblePointsToBuy > availbility[key] ? availbility[key] : AvailblePointsToBuy;
    AvailblePointsToBuy = (AvailblePointsToBuy - availbility[key]) > 0 ? (AvailblePointsToBuy - availbility[key]) :  0; 
  }
  priority++;
})
console.log(output);

Upvotes: 1

Related Questions