skip to Main Content

I have 3 objects

[
{name: 3, q: 10, b: 1},
{name: 5, q: 6, b: 2},
{name: 5, q: 7, b: 1}
]

I need to group them by name:

[
{name: 3: items: [{q:10, b: 1}]},
{name: 5: items: [{q:6, b: 2}, {q:7, b: 1}]},
]

maybe there are any delicate solutions with lodash?

4

Answers


  1. You can use Object.values combined with Array.prototype.reduce() and Array.prototype.push()

    Code:

    const data = [
      { name: 3, q: 10, b: 1 },
      { name: 5, q: 6, b: 2 },
      { name: 5, q: 7, b: 1 },
    ]
    
    const groupedData = Object.values(
      data.reduce((acc, obj) => {
        const { name, ...rest } = obj
        acc[name] = acc[name] || { name, items: [] }
        acc[name].items.push(rest)
        return acc
      }, {})
    )
    
    console.log(groupedData)
    Login or Signup to reply.
  2. You dont need lodash, you can just use JavaScript

    const inputArray = [
      {name: 3, q: 10, b: 1},
      {name: 5, q: 6, b: 2},
      {name: 5, q: 7, b: 1}
    ];
    

    using forEach

    function groupItemsByName(array) {
      // create a groups to store your new items
      const groups = {};
      
      //loop through your array
      array.forEach(obj => {
        // destructure each object into name and the rest 
        const { name, ...rest } = obj;
        // if the named group doesnt exist create that name with an empty array
        if (!groups[name]) {
          groups[name] = { name, items: [] };
        }
        // add the items to the named group based on the name
        groups[name].items.push(rest);
      });
    
      return Object.values(groups);
    }
    
    const transformedArray = groupItemsByName(inputArray);
    

    using reduce and Object.values()

    function groupItemsByName(array) {
      //Object.values returns an objects values as an array  
      return Object.values(
        array.reduce((groups, obj) => {
          // destructure as in the forEach method
          const { name, ...rest } = obj;
          // create the groups like in the previous method
          groups[name] = groups[name] || { name, items: [] };
          // push the items to the group based on the name
          groups[name].items.push(rest);
          return groups;
        }, {})
      );
    }
    
    
    const transformedArray = groupItemsByName(inputArray);
    

    using map and reduce

    const transformedArray = Array.from(
      inputArray.reduce((map, obj) => {
        const { name, ...rest } = obj;
        const existing = map.get(name) || { name, items: [] };
        existing.items.push(rest);
        return map.set(name, existing);
      }, new Map()).values()
    );
    

    output

    console.log(transformedArray);
    
    Login or Signup to reply.
  3. You can use the following simple solution to achieve this.

    const originalArr = [//This is your original input array
        { name: 3, q: 10, b: 1 },
        { name: 5, q: 6, b: 2 },
        { name: 5, q: 7, b: 1 }
    ];
    let filteredArr = [];
    originalArr.forEach(el => {
        const index = filteredArr.findIndex(__el => __el.name == el.name);
        if (index == -1) {//This means the current element does not exists in filtered array
            filteredArr.push({ name: el.name, items: [{ q: el.q, b: el.b }] });
        } else {
            filteredArr[index].items.push({ q: el.q, b: el.b });
        }
    });
    console.log(filteredArr);//You will get your desired output
    
    Login or Signup to reply.
  4. Hello simply you can use for loop with find function.

    i will try to help you Please check below example

    let mainArr = [
        { name: 3, q: 10, b: 1 },
        { name: 5, q: 6, b: 2 },
        { name: 5, q: 7, b: 1 },
    ];
    
    let setArr = [];
    
    for (let arr of mainArr) {
        let checkValue = setArr.find((e) => e.name.toString() === arr.name.toString());
    
        if (!checkValue) {
            setArr.push({ name: arr.name, items: [{ q: arr.q, b: arr.b }] });
        } else {
            checkValue.items.push({ q: arr.q, b: arr.b });
        }
    }
    
    console.log(JSON.stringify(setArr, null, 2));
    
    Result: [
        { name: 3, items: [{ q: 10, b: 1 }] },
        {
            name: 5,
            items: [
                { q: 6, b: 2 },
                { q: 7, b: 1 },
            ],
        },
    ];
    

    I hope this help you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search