DEV Community

mhsohag11
mhsohag11

Posted on

Answer: Merge 2 arrays of objects

Solution utilizing JS Map:

const merge = (arr1, arr2, prop) => {
    const resultMap = new Map(arr1.map((item) => [item[prop], item]))
    arr2.forEach((item) => {
        const mapItem = resultMap.get(item[prop]);
        if (mapItem) Object.assign(mapItem, item);
        else resultMap.set(item[prop], item);
    });
    return [...resultMap.values()];
};

const arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});

Top comments (0)