Home > OS >  Loop into array object then check if there's a equal value?
Loop into array object then check if there's a equal value?

Time:05-25

Question, I have this array object, I want to find out which of this array have a similar values then make them as one.

Example

[0:
        cartProduct: {
    category: "chair"
    color: "navy"
    id: "628a1738fd8299ae6659d994"
    image: "http://localhost:5000/../public/Product_chair_communal-navy.jpg"
    name: "The Communal"
    price: "4.30"
    }
        quantity: 1,
        1:
        cartProduct: {{
    category: "chair"
    color: "navy"
    id: "628a1738fd8299ae6659d994"
    image: "http://localhost:5000/../public/Product_chair_communal-navy.jpg"
    name: "The Communal"
    price: "4.30"
    }
        quantity: 1,

] For example the data above I want to know if they have the similar values interms of color if yes then only return one value.

Thanks!

CodePudding user response:

You can use this loop:

let uniqueArray = [];

dataArray.forEach((item, indx) => {
  let colorsArray = [];
  if (colorsArray.includes(item.color)) {
    continue;
  }
  uniqueArray.push(item);
})

CodePudding user response:

Not the cleanest, or most performant approach:

// function to group the items
const groupCartItems = (items, byProperties = ['color', 'id']) => {

    // utility funciton
    const verifyEquality = (itemA, itemB) => {
        let isEqual = true;
        byProperties.forEach((prop) => {
            if (itemA.cartProduct[prop] != itemB.cartProduct[prop]) {
                isEqual = false;
                break;
            }
        });
        return isEqual;
    };

    const groupedItems = [];

    items.forEach((item) => {
        // if item has been added, skip
        if (groupedItems.find((i) => verifyEquality(item, i))) {
            return;
        }
        // find equal items
        const equals = items.filter((i) => verifyEquality(item, i));
        // sum quantities
        const quantity = equals.reduce((previousValue, data) => previousValue   data.quantity, 0);
        // push
        groupedItems.push({
            cartProduct: item.cartProduct,
            quantity,
        });
    });

    return groupedItems;
};

For the 'similarity' stuff, I would recommend not to do this, because it is just not a good practise. Have your values equal or else!!!

Now seriously, check string-similarity. From documentation, you would only need to change the if inside verifyEquality function to:

import stringSimilarity from 'string-similarity';

// tweak this value to change how similar strings should be to be considered equal
const EQUALITY_RATIO = 0.75;

// ....

if (stringSimilarity.compareTwoStrings(itemA.cartProduct[prop], itemB.cartProduct[prop]) < EQUALITY_RATIO) {
}
  • Related