объединений массивов на js
Всем привет мне нужно объединить два массива с уникальными значениями у меня получилось но то гавно код я думаю можно сделать проще
const arrOne = [
{city: '111', price: 1},
{city: '222', price: 2},
]
const arrTwo = [
{city: '111', price: 0},
{city: '333', price: 0},
{city: '444', price: 0},
]
const res = arrOne.reduce((acc, cur, idx, def) => {
const findCity = arrTwo.filter(el => !def.find(it => it.city === el.city) )
console.log('findCity', findCity)
if(findCity && findCity.length > 0){
return [...acc, ...findCity, cur]
}
return [...acc, cur]
}, [])
console.log('res', [...new Set(res)] )
|
let stopArray = false
const res2 = arrOne.reduce((acc, cur, idx, def) => { const findCity = arrTwo.filter(el => !def.find(it => it.city === el.city)) if(findCity && findCity.length > 0 && !stopArray){ stopArray = true return [...acc, ...findCity, cur] } return [...acc, cur] }, []) console.log('2', res2) |
misha.korolcov,
const arrOne = [{
city: '111',
price: 1
},
{
city: '222',
price: 2
},
]
const arrTwo = [{
city: '111',
price: 0
},
{
city: '333',
price: 0
},
{
city: '444',
price: 0
},
]
const res = (...arr) => {
const obj = {};
return arr.flat().filter(ob => {
let {
city,
price
} = ob;
if (obj[city]) {
obj[city].price += price;
return false
} else {
obj[city] = ob
};
return true
})
}
console.log('res', res(arrOne, arrTwo))
|
рони, имхо, лучше такие вещи иммутабельно делать для надёжности:
const res = (...arr) => {
const acc = Object.create(null);
arr.flat().forEach(({ city, price, ...rest }) => {
if (acc[city]) {
acc[city].price += price;
} else {
acc[city] = { city, price, ...rest };
}
});
return Object.values(acc);
}
Но по задаче точно не скажешь. Впрочем по задаче не скажешь, что вообще надо что-то суммировать.) |
Aetae,
:) согласен! |
let arrOne = [
{city: '111', price: 1},
{city: '222', price: 2},
];
let arrTwo = [
{city: '111', price: 0},
{city: '333', price: 0},
{city: '444', price: 0},
];
function mergeArray(a1, a2){
let check = a1.map( el1 => el1.city );
let a2filtered = a2.filter( el2 => !check.includes(el2.city) );
return a1.concat(a2filtered);
}
console.log( mergeArray(arrOne, arrTwo) );
|
Белый шум, ты же понимаешь что твоя хрень будет через includes каждый раз перебирать весь массив, что приводит к квадратичной сложности?
|
Aetae,
Да. Я сначала запостил, потом посмотрел ваши варианты и понял что они лучше. |
| Часовой пояс GMT +3, время: 00:42. |