Tengo esta matriz y quiero sumar la propiedad ( y ) de los elementos de la matriz cuando x coincide con ciertos criterios. Por ejemplo, si "x" tiene el mismo valor de cadena entre "/" y "?" como otro objeto y luego agregue su propiedad "y".
const data = [ { "x": "/shop.html", "y": 3 }, { "x": "/", "y": 2 }, { "x": "/?test324", "y": 1 }, { "x": "/account.html", "y": 1 }, { "x": "/account.html?test1", "y": 1 }, { "x": "/shop.html?test543", "y": 1 } ]Y debería ser así al final.
const expectedResult = [ { "x": "/shop.html", "y": 4 }, { "x": "/", "y": 3 }, { "x": "/account.html", "y": 2 }, ]Entonces, como puede ver, la segunda matriz no tiene la cosa "? xxx", todos están "combinados" en función del valor de cadena entre el último "/" y "?"
Intenté hacer algo como esto
let output = res.data.data.reduce(function (accumulator, cur) { let x = cur.x, found = accumulator.find(function (elem) { elem.x = elem.x.split("?")[0]; return elem.x == x; }); if (found) found.y += cur.y; else accumulator.push(cur); return accumulator; }, []);Pero los valores duplicados no se agregan.
me devuelve esto
[ { "x": "/shop.html", "y": 3 }, { "x": "/", "y": 2 }, { "x": "/", "y": 1 }, { "x": "/account.html", "y": 1 }, { "x": "/account.html", "y": 1 }, { "x": "/shop.html?test543", "y": 1 } ]¿Alguna idea?
La siguiente puede ser una posible solución para lograr el objetivo deseado.
Fragmento de código
// a small helper method to convert key by leaving out the zs in: '/xxxx?zzz' const convertKey = x => (x.split('?')[0]); // use reduce to iterate thru the array & obtain a result-object // destructure to get 'x', 'y' // if 'x' already present, add 'y' // else create an object with 'x', 'y' props // return the `Object.values` of the result-object const transform = arr => ( Object.values( arr.reduce( (acc, {x, y}) => ({ ...acc, [convertKey(x)]: { ...(acc[convertKey(x)] || {x}), y: (acc[convertKey(x)]?.y || 0) + y } }), {} ) ) ); const data = [ { "x": "/shop.html", "y": 3 }, { "x": "/", "y": 2 }, { "x": "/?test324", "y": 1 }, { "x": "/account.html", "y": 1 }, { "x": "/account.html?test1", "y": 1 }, { "x": "/shop.html?test543", "y": 1 } ]; console.log(transform(data));Explicación
El fragmento de código anterior tiene comentarios en línea que describen los pasos. Para una descripción más detallada, publique preguntas específicas en los comentarios a continuación, si es necesario.