0

I have 2 arrays of objects. I would like to add a category property to each object in values, example: 50 should fall in the range 41 to 70

let values = [
    {1: 124},
    {2: 50},
    {3: 65},
    {4: 21}
];

let categories = [
    {cat: "Category1", min: 5, max: 40},
    {cat: "Category2", min: 41, max: 70},
    {cat: "Category3", min: 71, max: 130}
];

How do I get my result as, using array method forEach():

[
    {1: 124, category: "Category3"},
    {2: 50, category: "Category2"},
    {3: 65, category: "Category2"},
    {4: 21, category: "Category1"}
]

1 Answer 1

1

Not an optimized one but satisfies the requirement.

let result = [];
values.forEach(element => {
    categories.forEach(col => {
        let current = Object.values(element)[0];
        if(current >= col.min && current <=col.max){ 
            element["category"] = col.cat;
        }
    })
    result.push(element);
})
Sign up to request clarification or add additional context in comments.

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.