簡體   English   中英

循環進入數組對象然后檢查是否有相等的值?

[英]Loop into array object then check if there's a equal value?

問題,我有這個數組對象,我想找出這個數組中的哪一個具有相似的值,然后將它們作為一個。

例子

[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,

] 例如,我想知道上面的數據在顏色方面是否具有相似的值,如果是,則只返回一個值。

謝謝!

你可以使用這個循環:

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

不是最干凈或最高效的方法:

// 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;
};

對於“相似性”的東西,我建議不要這樣做,因為這不是一個好習慣。 讓你的價值觀相等,否則!!!

現在認真地檢查string-similarity 從文檔中,您只需將if inside verifyEquality函數更改為:

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) {
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM