-2

I have an array that contains objects. The array looks like this:

[
    {
        "number": "10a",
        "person": "Velvet"
    },
    {
        "number": "10b",
        "person": "Edna"
    },
    {
        "number": "11a",
        "person": "Shionne"
    },
    {
        "number": "11b",
        "person": "Aifread"
    },

]

I want to combine objects that have identical number property. For example, the first two objects have property number: "10a", and number: "10b". I want these to be combined such that the output becomes:

{
    "10": {
       "person": ["Velvet", "Edna"]
    },
    "11": {
       "person": ["Shionne", "Aifread"]
    }
}

I am not sure how to do it as it seems too complicated for me. I also looked over stackoverflow but can't seem to find a similar problem, hence, my post. Thanks for the help!

11
  • Is number has fixed length 3? If not ,it will be difficult to define similar Commented Jan 13, 2023 at 11:34
  • @flyingfox, yep. The number has a fixed length of 3. Commented Jan 13, 2023 at 11:34
  • @Agida,I think this problem is worth answering Commented Jan 13, 2023 at 11:35
  • Can we reopen the problem? The suggested answer doesnt answer my probem. Thanks Commented Jan 13, 2023 at 11:35
  • 1
    Ther are plenty of articles and questions about array transformations. Good articles is here medium.com/@jasminegump/… What is your number format? always any number and one letter? Commented Jan 13, 2023 at 11:35

2 Answers 2

1

I'll assume that the normalization for number is just to remove non numeric characters. If so, you can just iterate over the original array and process each element:

var original = [
    {
        "number": "10a",
        "person": "Velvet"
    },
    {
        "number": "10b",
        "person": "Edna"
    },
    {
        "number": "11a",
        "person": "Shionne"
    },
    {
        "number": "11b",
        "person": "Aifread"
    },
];

const merged = {}
    
        original.forEach(item => {
            var normalizedKey = item.number.replaceAll( /\D/g, "" )
            if(!merged[normalizedKey]) merged[normalizedKey] = { person: []}
            merged[normalizedKey].person.push(item.person)
        })
        
        console.log({merged})
    

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

1 Comment

I knew there was a way to loop only once but I couldn't figure it out! This was the answer I am looking for! Thank you very much!
0

Parse number. Add object if missing and append name:

const result = {};
arr.forEach(o => {
    const nr = o.number.slice(0,2);
    result[nr] = result[nr] || {person:[]};
    result[nr].person.push(o.person);
});

console.log(result);

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.