Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split an array into two based on condition using javascript

I have an array of objects like this below.

[
    {
        product_id: 4,
        product_name: "Samsung",
        category_name: "Tv and home appliance",
        is_Available: 1
    },
    {
        product_id: 8,
        product_name: "Apple",
        category_name: "Home gadgets",
        is_Available: 1
    },
    {
        product_id: 9,
        product_name: "Verifone",
        category_name: "Electronics",
        is_Available: 0
    }
  ]

I want to split this array into two based on is_Available flag value. So i did like this using reduce.

const formmattedResponse = data.reduce((arr,el) => {
            if(el.is_Available === 1) {
                arr.push({...el});
            }
            return arr;
        },[]);

But, i need this type of formatted data like below based on above data array

{
    availableData: [{
        product_id: 4,
        product_name: "Samsung",
        category_name: "Tv and home appliance",
        is_Available: 1
    },
    {
        product_id: 8,
        product_name: "Apple",
        category_name: "Home gadgets",
        is_Available: 1
    }
   ],
  notAvailableData: [{
        product_id: 9,
        product_name: "Verifone",
        category_name: "Electronics",
        is_Available: 0
    }
   ]
  }
like image 584
learningMonk Avatar asked May 09 '26 01:05

learningMonk


1 Answers

UPDATE 2024

With Object.groupBy, it goes shorter by taking a group value.

const
    data = [{ product_id: 4, product_name: "Samsung", category_name: "Tv and home appliance", is_Available: 1 }, { product_id: 8, product_name: "Apple", category_name: "Home gadgets", is_Available: 1 }, { product_id: 9, product_name: "Verifone", category_name: "Electronics", is_Available: 0 }],
    result = Object.groupBy(data, ({ is_Available }) => is_Available
        ? 'availableData'
        : 'notAvailableData'
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You could take an array and push the objects according their availability with a single loop.

const
    data = [{ product_id: 4, product_name: "Samsung", category_name: "Tv and home appliance", is_Available: 1 }, { product_id: 8, product_name: "Apple", category_name: "Home gadgets", is_Available: 1 }, { product_id: 9, product_name: "Verifone", category_name: "Electronics", is_Available: 0 }],
    result = data.reduce((r, o) => {
        r[o.is_Available ? 'availableData' : 'notAvailableData'].push(o);
        return r;
    }, { availableData: [], notAvailableData: [] });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 69
Nina Scholz Avatar answered May 10 '26 14:05

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!