I am having the array of objects like below
Array 1:
[{id: 1, name: 'Golden', isEdited: true}, {id: 2, name: 'Pearl'}]
Array 2:
[{id: 1, name: 'Golden'}, {id: 2, name: 'Pearlblue'}, , {id: 3, name: 'Orange'}]
Now i would like to merge the two arrays if the object contains isEdited flag means then that object should not be updated.
Expected result should be
[{id: 1, name: 'Golden', isEdited: true}, {id: 2, name: 'Pearlblue'}, {id: 3, name: 'Orange'}]
I have tried with the below approach
b.map((battr) => {
return {
...a[battr.id],
...battr
}
})
But it returns the output as
[{id: 1, name: 'Golden'}, {id: 2, name: 'Pearlblue'}, {id: 3, name: 'Orange'}]
Be carefull, your ids don't match your array indexes.
Hence in your attempt a[battr.id] should be replaced by something like a.find(a => a.id === battr.id)
Your example is confusing since in both arrays the name is 'Golden' for id=1, but assuming you want only the properties from array A if isEdited=true, your solution could be :
b.map((b_attr) => {
var matchingA = a.find(a_attr => a_attr.id === b_attr.id);
if (matchingA && matchingA.isEdited)
return matchingA;
else
return { ...matchingA, ...b_attr }
})
Related
I have 2 array of objects like
const arrayOne = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
const arrayTwo = [{id: 2, name: 'two'}, {id: 3, name: 'three'}];
Here, I need to compare both these arrays and remove matching objects from arrayOne, which should finally give
this.arrayOne = [{id: 1, name: 'one'}];
I tried like below but it is removing all objects from the array
this.arrayOne = this.arrayOne.filter(o1 => this.arrayTwo.some(o2 => o1.id === o2.id));
What I am doing wrong here? Please suggest. Thanks
const arrayOne = [
{ id: 1, name: "one" },
{ id: 2, name: "two" },
{ id: 3, name: "three" },
];
const arrayTwo = [
{ id: 2, name: "two" },
{ id: 3, name: "three" },
];
const arrayTwoIds = new Set(arrayTwo.map((el) => el.id));
const arrayOneFiltered = arrayOne.filter((el) => !arrayTwoIds.has(el.id));
console.log(arrayOneFiltered);
// [ { id: 1, name: 'one' } ]
Depending on the size of the array, creating a set can improve performance, as you do not need to loop over arrayTwo arrayOne.length times but only once. After that, you can look up the existence of an id in arrayTwo in constant time.
Yet, as pointed out in another answer, this is not necessary if the arrays are small (like in your example). In this case, you could also use this one-liner:
arrayOne = arrayOne.filter((elOne) => !arrayTwo.some((elTwo) => elOne.id === elTwo.id));
Here, arrayOne would need to be mutable, i.e. defined with let.
You can find it by comparing it with id.
And arrayOne must be a let.
let arrayOne = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
const arrayTwo = [{id: 2, name: 'two'}, {id: 3, name: 'three'}];
arrayOne = arrayOne.filter(one => !arrayTwo.find(two => one.id == two.id));
console.log(arrayOne);
const arrayOne = [{
id: 1,
name: 'one'
}, {
id: 2,
name: 'two'
}, {
id: 3,
name: 'three'
}];
const arrayTwo = [{
id: 2,
name: 'two'
}, {
id: 3,
name: 'three'
}];
const arrayTwoId = arrayTwo.map(el => (el.id)); // extract id from arrayTwo
const result = arrayOne.filter(el => !arrayTwoId.includes(el.id));
console.log(result);
Extract all the ids from the arrayTwo.
filter those objects who do not match the array of ids of arrayTwo.
Your way is correct. but you miss the not operation (!) before arrayTwo.some.
So the correct way is this:
const arrayOne = [
{id: 1, name: 'one'},
{id: 2, name: 'two'},
{id: 3, name: 'three'}
];
const arrayTwo = [
{id: 2, name: 'two'},
{id: 3, name: 'three'}
];
// Shared Items between arrayOne and arrayTwo (this what you done)
const sharedObjects = arrayOne.filter(o1 => arrayTwo.some(o2 => o1.id === o2.id));
console.log(sharedObjects);
// arrayOne - arrayTwo (this is what you want)
const arrayOneUniqueObjects = arrayOne.filter(o1 => !arrayTwo.some(o2 => o1.id === o2.id));
console.log(arrayOneUniqueObjects);
Also, You can find more details here:
bobbyhadz.com/blog/javascript-get-difference-between-two-arrays-of-objects
const censusMembers = Object.freeze([
{
id: 1,
name: 'Bob'
}, {
id: 2,
name: 'Sue'
}, {
id: 3,
name: 'Mary',
household_id: 2
}, {
id: 4,
name: 'Elizabeth',
household_id: 6
}, {
id: 5,
name: 'Tom'
}, {
id: 6,
name: 'Jill'
}, {
id: 7,
name: 'John',
household_id: 6
}
]);
In this array, A dependent can be determined by the presence of a household_id. The household_id is a reference to the ID of the employee that that member is a depended of (ex in the censusMembers list 'Mary' is a dependent of 'Sue')
How to build a function that takes in an id and the array of members(census members) and returns all dependents that belong to the user that has that id.
If the id is of a dependent, or isn't in the censusMember array then the function should return null.
If there are no dependents then the function should return an empty arrray.
for example:
if I give input as id 6
then output shoul be
[
{"id":4,"name":"Elizabeth","household_id":6},
{"id":7,"name":"John","household_id":6}
]
Here is code that seems to do what you would like:
const {curry, find, propEq, has, filter} = R
const householdMembers = curry((census, id) => {
const person = find(propEq('id', id), census);
return person
? has('household_id', person)
? null
: filter(propEq('household_id', id), census)
: null
})
var censusMembers = Object.freeze([
{id: 1, name: 'Bob'},
{id: 2, name: 'Sue' },
{id: 3, name: 'Mary', household_id: 2 },
{id: 4, name: 'Elizabeth', household_id: 6},
{id: 5, name: 'Tom'},
{id: 6, name: 'Jill'},
{id: 7, name: 'John', household_id: 6}
])
const householders = householdMembers(censusMembers)
console.log(householders(6))
//=> [
// {id: 4, name: 'Elizabeth','household_id': 6},
// {id: 7, name: 'John', 'household_id': 6}
// ]
console.log(householders(7)) //=> null
console.log(householders(8)) //=> null
console.log(householders(5)) //=> []
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
But I would suggest that you might want to rethink this API. The empty array is a perfectly reasonable result when nothing is found. Making it return null for some of these cases makes the output much harder to use. For instance, if you wanted to retrieve the list of names of household members, you could simply write const householderNames = pipe(householders, prop('name')). Or you could do this if your function always returned a list.
Having a single function return multiple types like this is much harder to understand, and much, much harder to maintain. Note how much simpler the following version is, one that always returns a (possibly empty) list:
const members = curry((census, id) => filter(propEq('household_id', id), census))
I have two arrays
let a1 = [{id: 1, name: "terror"}, {id: 2, name: "comics"}, {id: 3, name: "suspense"}]
let a2 = [{id: 1, name: "terror"}, {id: 3, name: "suspense"}]
I need to compare these arrays against each other and come out with something like this:
[{id: 1, name: "terror", selected: true}, {id: 2, name: "comics", selected: false}, {id: 3, name: "suspense", selected: true}]
I tried using filter below, but it didn't work, what should I do?
a2.filter(data => {
return a1.find(value => {
let x = data.id === value.id ? {
id: value.id,
text: value.name,
selected: true
} : {
id: data.id,
text: data.name,
selected: false
}
})
})
You shouldn't use filter because you need an output array that has the same number of items you started with - use map instead, to create a new array which has the same number of elements as the original array, only transformed.
Since it looks like a2 doesn't have any new information, and is only useful by showing the existence or abscence of some objects, a method with low complexity would be to map a2 to a Set of ids, and then generate the new objects by iterating over a1 and checking whether their ids are in the Set:
let a1 = [{id: 1, name: "terror"}, {id: 2, name: "comics"}, {id: 3, name: "suspense"}]
let a2 = [{id: 1, name: "terror"}, {id: 3, name: "suspense"}]
const a2IDs = new Set(a2.map(({ id }) => id));
const output = a1.map((item) => ({ ...item, selected: a2IDs.has(item.id) }));
console.log(output);
It would be possible to fix up your code so that it works, changing .filter to .map and using .find as you are, but it'll have greater complexity because it'll have to iterate over items in a2 each time (Set lookups by comparison are O(1)).
Is it possible to concat two arrays with objects and let the second array overwrite the first array where they have the same id:
// array 1
[
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
]
// array 2:
[
{id: 1, name: "newFoo"},
{id: 4, name: "y"},
{id: 5, name: "z"}
]
// out:
[
{id: 1, name: "newFoo"}, // overwriten by array 2
{id: 2, name: "bar"}, // not changed (from array 1)
{id: 3, name: "baz"}, // not changed (from array 1)
{id: 4, name: "y"}, // added (from array 2)
{id: 5, name: "z"} // added (from array 2)
]
If it is possible I would like to do this without the use of third party libraries
var a = [
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
];
var b = [
{id: 1, name: "fooboo"},
{id: 4, name: "bar"},
{id: 5, name: "baz"}
];
/* iterate through each of b, if match found in a, extend with that of a. else push into b ...*/
b.forEach(m => {
var item = a.find(n => n.id === m.id);
if(item) { return Object.assign(item, m); }
a.push(m);
});
console.log(a);
You can do
let arr1 = [
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
]
let arr2 = [
{id: 1, name: "newFoo"},
{id: 4, name: "y"},
{id: 5, name: "z"}
]
let result = arr1.concat(arr2).reduce((a, b) => {
a[b.id] = b.name;
return a;
},{})
result = Object.keys(result).map(e => {
return {id : e, name : result[e]};
});
console.log(result);
Explanation
I am using the property of objects that they don't keep duplicate keys, so for an array concated together, I reduce it to an object with id as it's key and name as its value, hence overriding all duplicates. In the next step I converted this back into an array.
Check you my solution. There is no "rewrite", i just use a second array as base and don't write value if it has same id.
let a = [
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
];
let b = [
{id: 1, name: "newFoo"},
{id: 4, name: "y"},
{id: 5, name: "z"}
];
let duplicateId;
a.forEach(aitem => {
duplicateId = false;
b.forEach(bitem => {
if (aitem.id === bitem.id)
duplicateId = true;
});
if (!duplicateId)
b.push(aitem);
});
console.log(b);
Maybe you can use Object.assign and Object.entries to achieve, lets say:
const arr1 = [
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
]
const arr2 = [
{id: 1, name: "newFoo"},
{id: 4, name: "y"},
{id: 5, name: "z"}
]
const obj3 = Object.entries(Object.assign({}, ...arr1, arr2))
.map(([prop, value]) => ({[prop]:value}));
Example:
https://jsfiddle.net/0f75vLka/
Another option would be to convert arrays to map with id as key then merge the objects and then convert it back to array.
var arr1 = [
{id: 1, name: "foo"},
{id: 2, name: "bar"},
{id: 3, name: "baz"}
];
var arr2 = [
{id: 1, name: "newFoo"},
{id: 4, name: "y"},
{id: 5, name: "z"}
];
function arr2map(arr) {
var map = {};
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
map[item.id] = item;
}
return map;
}
function map2arr(map) {
var arr = [];
for (var i in map) {
arr.push(map[i]);
}
return arr;
}
var arr1m = arr2map(arr1);
var arr2m = arr2map(arr2);
var arr3m = map2arr( Object.assign({}, arr1m, arr2m) );
//output
alert(JSON.stringify(arr3m));
I need to find a simplest way for setting order to array of objects.
For example, there is an array:
var array = [
{id: 1, name: "Matt"},
{id: 2, name: "Jack"},
{id: 3, name: "Morgan"},
{id: 4, name: "Bruce"}
];
and I have provided
var order = [1,4,2,3];
which refers to object id property of array items.
Now I need to reorder array so it should be like:
var array = [
{id: 1, name: "Matt"},
{id: 4, name: "Bruce"},
{id: 2, name: "Jack"},
{id: 3, name: "Morgan"}
]
Use Array#sort method for sorting and inside custom sort function use Array#indexOf method to get index.
var array = [{
id: 1,
name: "Matt"
}, {
id: 2,
name: "Jack"
}, {
id: 3,
name: "Morgan"
}, {
id: 4,
name: "Bruce"
}];
var order = [1, 4, 2, 3];
array.sort(function(a, b) {
// sort based on the index in order array
return order.indexOf(a.id) - order.indexOf(b.id);
})
console.log(array);
You can also use reduce() on [1,4,2,3] array to return object where keys will be elements and values will be index of each element and then sort by that object.
var array = [
{id: 1, name: "Matt"},
{id: 2, name: "Jack"},
{id: 3, name: "Morgan"},
{id: 4, name: "Bruce"}
];
var s = [1,4,2,3].reduce((r, e, i) => {return r[e] = i, r}, {});
var result = array.sort(function(a, b) {
return s[a.id] - s[b.id];
});
console.log(result)
I guess anything that involves sort can not be more efficient than an O(2n) solution. So i would like to do this job with two reduces as follows;
var arr = [{id: 1, name: "Matt"}, {id: 2, name: "Jack"}, {id: 3, name: "Morgan"}, {id: 4, name: "Bruce"}],
order = [1,4,2,3],
lut = order.reduce((t,e,i) => (t[e] = i,t),{}),
result = arr.reduce((res,obj) => (res[lut[obj.id]] = obj, res) ,[]);
console.log(result);