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
I am trying to compare two arrays of objects based on their IDs and return a boolean. I have filtered out items from the both arrays based on is_selected === 1. If IDs of both arrays are same will return isModified false or it will return true.
Both of these are an array of checkboxes. The initial array is what I am getting from the backend and the current is modified by the user. The current array length can be changed by changing checkboxes.
With my current approach for loop is not executing from the second time.
function cancel() {
const initialArr = [
{id: 8, name: "Celery", is_selected: 1},
{id: 9, name: "Crustaceans", is_selected: 1},
{id: 2, name: "Eggs", is_selected: 1},
{id: 6, name: "Fish", is_selected: 1},
];
const currentArr = [
{id: 8, name: "Celery", is_selected: 1},
{id: 4, name: "Mustard", is_selected: 1},
{id: 2, name: "Eggs", is_selected: 1},
{id: 6, name: "Fish", is_selected: 1},
];
let isModified!: boolean;
for (let index = 0; index < currentArr.length; index++) {
const id = currentArr[index].id;
isModified = initialArr.some((o2) => o2.id !== id);
if (isModified) break;
}
if(isModified){
alert('are you sure?');
} else {
console.log('exit the page');
}
}
There's no issue with the for loop in your code. There are few changes that you could do to improve it
Use a map instead of an array for faster lookups. Running an iteration on array everytime is slow, and it will only increase as the size of arr grows.
Check-in each iteration if the value is changed in the currentArr.
You also need to establish what will happen when there is a new item in the currentArr(i.e with new id), will it be counted as modified or as not modified?
Assuming the answer to the above question is yes, the below code should work
function cancel() {
const initialArr = [
{id: 8, name: "Celery", is_selected: 1},
{id: 9, name: "Crustaceans", is_selected: 1},
{id: 2, name: "Eggs", is_selected: 1},
{id: 6, name: "Fish", is_selected: 1},
];
const initalArrMap = initialArr.reduce((prev, current) => {
return {...prev, [current.id]: current}
}, {});
const currentArr = [
{id: 8, name: "Celery", is_selected: 1},
{id: 9, name: "Mustard", is_selected: 1},
{id: 2, name: "Eggs", is_selected: 1},
{id: 6, name: "Fish", is_selected: 1},
{id: 9, name: "Fish", is_selected: 1},
];
let isModified = currentArr.length !== initialArr.length;
if(!isModified){
for (let index = 0; index < currentArr.length; index++) {
const id = currentArr[index].id;
isModified = initalArrMap[id] ? initalArrMap[id].is_selected != currentArr[index].is_selected : true;
if (isModified) break;
}
}
if(isModified){
alert('are you sure?');
} else {
console.log('exit the page');
}
}
cancel();
Note: I am only checking if is_selected is changed to determine if the currentArr is changed.
Edit: Added a check in case currentArr and initialArr length are not equal
The problem is using initialArr.some((o2) => o2.id !== id).
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false.
What do you want to check? If initialArr does not have currentArr ids, it means my currentArr is modified, so you need to try this one:
!initialArr.some((o2) => o2.id === id)
const initialArr = [
{ id: 8, name: "Celery", is_selected: 1 },
{ id: 9, name: "Crustaceans", is_selected: 1 },
{ id: 2, name: "Eggs", is_selected: 1 },
{ id: 6, name: "Fish", is_selected: 1 }
];
const currentArr = [
{ id: 8, name: "Celery", is_selected: 1 },
{ id: 4, name: "Mustard", is_selected: 1 },
{ id: 2, name: "Eggs", is_selected: 1 },
{ id: 6, name: "Fish", is_selected: 1 }
];
let isModified = false;
for (let index = 0; index < currentArr.length; index++) {
const id = currentArr[index].id;
isModified = !initialArr.some((o2) => o2.id === id);
if (isModified)
break;
}
if (isModified) {
alert('are you sure?');
} else {
console.log('exit the page');
}
It will compare each element of first array with all elements of 2nd array
sorting key will make sure it gives correct result if sequence of keys are changed .
it will break the loop as soon as it finds the first different object.
function cancel() {
const a = [
{id: 8, name: "Celery", is_selected: 1},
{id: 9, name: "Crustaceans", is_selected: 1},
{id: 2, name: "Eggs", is_selected: 1},
{id: 6, name: "Fish", is_selected: 1},
];
const b = [
{id: 8, name: "Celery", is_selected: 1},
{id: 4, name: "Mustard", is_selected: 1},
{id: 2, name: "Eggs", is_selected: 1},
{id: 6, name: "Fish", is_selected: 1},
];
let isModified;
let ctr =0;
for (let index = 0; index < a.length; index++) {
for(let j=0; j<b.length; j++){
var aKeys = Object.keys(a[index]).sort();
var bKeys = Object.keys(b[j]).sort();
if(aKeys.toString()!== bKeys.toString()){
ctr++;
break;
}
}
}
if(ctr){
alert('Modified');
} else {
console.log('not modified');
}
}
cancel();
The reason it was returning true for every item in the array is not because of logic error but syntax error, check your array of Objects they don't have commas that separate array elements
My apologies if this has been addressed before, but I couldn't get it to work with anything I found.
Assume I have 2 arrays - arr1, arr2. I want to update the objects in arr1 if the the property id matches in arr1 and arr2. Objects that exist in arr2 but not in arr1 - meaning the property id does not exist in arr1 - should be pushed to arr1.
Example:
let arr1 = [
{id: 0, name: "John"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
]
let arr2 = [
{id: 0, name: "Mark"},
{id: 4, name: "Sara"}
]
# Expected Outcome
let outcome = [
{id: 0, name: "Mark"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"},
{id: 4, name: "Sara"}
]
You can use reduce and find for this:
const arr1 = [
{id: 0, name: "John"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
];
const arr2 = [
{id: 0, name: "Mark"},
{id: 4, name: "Sara"}
];
arr2.reduce((res, item) => {
const existingItem = res.find(x => x.id === item.id);
if (existingItem) { existingItem.name = item.name; }
else { res.push(item); }
return res;
}, arr1);
console.log(arr1);
You could do this:
let arr1 = [
{id: 0, name: "John"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
]
let arr2 = [
{id: 0, name: "Mark"},
{id: 4, name: "Sara"}
]
var res = arr1.reduce((acc, elem)=>{
var x = arr2.find(i=>i.id === elem.id);
if(x){
acc.push(x)
}else{
acc.push(elem)
}
return acc
}, []);
console.log(res)
Assuming you want to mutate the objects in arr1 rather than creating new ones, one way to do it would be using for...of to iterate the objects in arr2 and then check if there's already an object with the same id in arr1 using Array.prototype.find():
If there is one, you mutate it with Object.assign.
Otherwise, push the new object to arr1:
const arr1 = [
{ id: 0, name: 'John' },
{ id: 1, name: 'Sara' },
{ id: 2, name: 'Domnic' },
{ id: 3, name: 'Bravo' },
];
const arr2 = [
{ id: 0, name: 'Mark', sometingElse: 123 },
{ id: 2, foo: 'bar' },
{ id: 4, name: 'Sara' },
];
for (const currentElement of arr2) {
let previousElement = arr1.find(el => el.id === currentElement.id);
if (previousElement) {
Object.assign(previousElement, currentElement);
} else {
arr1.push(currentElement);
}
}
console.log(arr1);
.as-console-wrapper {
max-height: 100% !important;
}
if you want to try something different you can use foreach and filter to achieve this
let arr1 = [
{id: 0, name: "John"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
]
let arr2 = [
{id: 0, name: "Mark"},
{id: 4, name: "Sara"}]
arr1.forEach(x=>{
arr2.forEach(y=>{
if(x.id==y.id){
x.name=y.name
}
})
})
arr2.filter((a)=>{if(!arr1.some(b=>a.id==b.id)) arr1.push(a)})
console.log(arr1)
You should be able to use Array.prototype.find to sort this out!
let arr1 = [
{id: 0, name: "John"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
];
let arr2 = [
{id: 0, name: "Mark"},
{id: 4, name: "Sara"}
];
let updateArrayOfObjects = (arr1, arr2) => {
for (let obj of arr2) {
let item = arr1.find(v => v.id === obj.id);
if (item) item.name = obj.name;
else arr1.push({ ...obj });
}
return arr1;
};
console.log(updateArrayOfObjects(arr1, arr2));
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);