Get diff between two arrays of objects with ES6 or TypeScript - arrays

I have the following arrays:
arr1 = [{
id: 1,
name: 'Diego',
age: 23
}, {
id: 2,
name: 'Brian',
age: 18
}]
arr2 = [{
id: 1,
name: 'Diego',
age: 23
}, {
id: 2,
name: 'Brian',
age: 18
}, {
id: 3,
name: 'Pikachu',
age: 88
}]
I need get difference between this two arrays, the espected result is:
arr3 [{id:3, name: 'Pikachu', age: 88}]
How do i solve this problem using ES6 or TypeScript?
I tried using SET, but doesn't worked.

Something like this maybe:
let ids1 = arr1.map(item => item.id);
let ids2 = arr2.map(item => item.id);
let diff = ids1.map((id, index) => {
if (ids2.indexOf(id) < 0) {
return arr1[index];
}
}).concat(ids2.map((id, index) => {
if (ids1.indexOf(id) < 0) {
return arr2[index];
}
})).filter(item => item != undefined);
(code in playground)

Related

How to manipulate the object inside the array using javascript?

var arr = [
{ id: 1, name: 'Ahmed Malick', school: 'TEWGS' },
{ id: 2, name: 'Tehmeed Anwar', school: 'DGS' },
{ id: 3, name: 'Azhar Yameen', school: 'DGS' }
]
I want this output:
The student name is his id is and he studies in
Can you please show me what kind of output you expect. Then i will try to solve it.
I'm not sure if this is what you want
var arr = [
{ id: 1, name: "Ahmed Malick", school: "TEWGS" },
{ id: 2, name: "Tehmeed Anwar", school: "DGS" },
{ id: 3, name: "Azhar Yameen", school: "DGS" },
];
arr.map((student) => {
return `Name: ${student.name}, id: ${student.id}, he studies in: ${student.school}`;
}).forEach((output) => {
console.log(output);
});
If you want it in the DOM do this
let html = arr.map((student) => {
return `<p><strong>Name</strong>: ${student.name}, <strong>id</strong>: ${student.id},<strong> he studies in</strong> ${student.school}</p>`;
}).join("")
document.createElement("div").innerHTML = html
Try thatGood luck

Create new array using 2 arrays with Map function in Angular

Is there an efficient way of creating a new array from 2 arrays?
var employees1 = [
{ id: 11, name: 'joe' },
{ id: 12, name: 'mike' },
{ id: 13, name: 'mary' },
{ id: 14, name: 'anne' }
];
var employees2 = [
{ id: 11, message: 'test1' },
{ id: 12, message: 'test2' },
{ id: 13, message: 'test3' },
{ id: 14, message: 'test4' }
];
Iterate employees1 array and get 'message' for matching id from employees2. Resulting in new array:
var employees3 = [
{ id: 11, name: 'joe', message: 'test1' },
{ id: 12, name: 'mike', message: 'test2' },
{ id: 13, name: 'mary', message: 'test3' },
{ id: 14, name: 'anne', message: 'test4' }
];
Is this possible using Map function? Or using a standard foreach suggested?
Iterate over the first array, search for the element in the second array and finally push them to the new array as illustrated below:
var employees3 = [];
employees1.forEach(emp1 => {
const findEmp = employees2.find(emp2 => emp2.id === emp1.id);
if (findEmp) {
employees3.push({
...emp1,
...findEmp
});
}
});
console.log(employees3);
You can use Array#map and Array#find to get the desired output. I am attaching a sample code:
var employees3 = employees1.map(emp => ({
...emp,
...(employees2.find(item => item.id === emp.id) ?? {})
}))

How to check if arrays have the same object React Native [duplicate]

This question already has answers here:
An efficient way to get the difference between two arrays of objects?
(4 answers)
Closed 3 years ago.
I have two arrays:
const array1 = [
{ id: 1, name: 'John', score: 124 },
{ id: 2, name: 'Angie', score: 80 },
{ id: 3, name: 'Max', score: 56 }
]
const array2 = [
{ id: 5, name: 'Lisa', score: 78 },
{ id: 2, name: 'Angie', score: 80 }
]
JSON.stringify(array1) == JSON.stringify(array2) is not a solution, because arrays have different number of objects.
array1.some(item=> array2.includes(item)) doesnt't work too.
If there a solution?
What i would suggest is since your id is unique , so try the below :
const array1 = [
{ id: 1, name: 'John', score: 124 },
{ id: 2, name: 'Angie', score: 80 },
{ id: 3, name: 'Max', score: 56 }
]
const array2 = [
{ id: 5, name: 'Lisa', score: 78 },
{ id: 2, name: 'Angie', score: 80 }
]
var array2Id = {}
array2.forEach(function(obj){
bIds[obj.id] = obj;
});
// Return all elements in A, unless in B
let check = array1.filter(function(obj){
return !(obj.id in array2Id);
});
console.log(check,'there')
if check is an empty array that means both are same otherwise it will give the different objects.
Hope it helps feel free for doubts
Here is a quick solution, maybe not the most performant.
const array1 = [
{ id: 1, name: 'John', score: 124 },
{ id: 2, name: 'Angie', score: 80 },
{ id: 3, name: 'Max', score: 56 },
];
const array2 = [
{ id: 5, name: 'Lisa', score: 78 },
{ id: 2, name: 'Angie', score: 80 },
];
// Index will have -1 if there is no match, otherwise it'll have
// the index of the first found match in array1.
const index = array1.findIndex(array1Item => {
// This will return the index if found, otherwise -1
const match = array2.findIndex(array2Item => {
// return array1Item.id === array2Item.id;
return JSON.stringify(array1Item) === JSON.stringify(array2Item);
});
return match > -1;
});
Instead of stringifying the entire object, if id is unique, you can just compare id as shown in the commented code.
Be advised this could have a complexity of O(n^2) where n is your array sizes. Big arrays may take a while.
Here is it running on PlayCode. It logs index as 1 because the first match is the second item in array1.

Filter an Array based on multiple values

I have the following simple JSON array:
const personList = [
{
id: 1,
name: "Phil"
},
{
id: 2,
name: "Bren"
},
{
id: 3,
name: "Francis Underwood"
},
{
id: 4,
name: "Claire Underwood"
},
{
id: 5,
name: "Ricky Underwood"
},
{
id: 6,
name: "Leo Boykewich"
}
];
And I would like to filter this by passing an array of ids so something like [1,4] would be passed in and it would only return "Phill" and "Claire Underwood"
This is what the function looks like but I know it's wrong attendeeIds is an array that's passed in [1, 4]:
getAttendeesForEvent: (attendeeIds) => {
if (attendeeIds === undefined) return Promise.reject("No attendee id provided");
return Promise.resolve(personList.filter(x => x.id == [attendeeIds]).shift());
}
I haven't used JS in years. I've looked for examples but they all seem too complex for what I'm trying to achieve. So how can I filter this based on an array of id's passed in?
return Promise.resolve(personList.filter(x => attendeeIds.indexOf(x.id) !== -1));
You want to check if the id of each item your looping over exists inside of attendeeIds. Use Array.indexOf inside of the filter to do that.
This will return an array of { id: #, name: String } objects.
If you want to return just the names of those objects, you can do a map afterwards which will transform an array into another array using the function that you provide.
const filteredNames = personList
.filter(x => attendeeIds.indexOf(x.id) !== -1)
.map(x => x.name);
// ['Phil', 'Claire Underwood']
You could do something in these lines. Hope this helps.
const personList = [{
id: 1,
name: "Phil"
}, {
id: 2,
name: "Bren"
}, {
id: 3,
name: "Francis Underwood"
}, {
id: 4,
name: "Claire Underwood"
}, {
id: 5,
name: "Ricky Underwood"
}, {
id: 6,
name: "Leo Boykewich"
}];
let attendeeIds = [1, 5];
let getAttendeesForEvent = () => {
return new Promise(function(resolve, reject) {
if (attendeeIds === undefined) {
reject("No attendee id provided");
} else {
resolve(personList.filter((x) => attendeeIds.includes(x.id)).map((obj) => obj.name));
}
});
}
getAttendeesForEvent().then((data) => console.log(data))

Angular show list in alphabetical order and also show divider

**please anyone can help me i want to print list in Angularjs like this **
enter image description here
Use Order by
$scope.friends = [
{name: 'John', phone: '555-1212', age: 10},
{name: 'Mary', phone: '555-9876', age: 19},
{name: 'Mike', phone: '555-4321', age: 21},
{name: 'Adam', phone: '555-5678', age: 35},
{name: 'Julie', phone: '555-8765', age: 29}
];
<tr ng-repeat="friend in friends | orderBy:'name'">
read more here
You have to filter each group by the letters you want. Here's a Plunker Using this list:
$scope.myList = [{
id: 11,
name: 'Okra'
}, {
id: 12,
name: 'Musa'
}, {
id: 4,
name: 'Sky'
}, {
id: 13,
name: 'India'
}, {
id: 14,
name: 'Rose'
}, {
id: 15,
name: 'Titanic'
}, {
id: 16,
name: 'Onion'
}, {
id: 6,
name: 'Germany'
}, {
id: 17,
name: 'Beer'
}, {
id: 18,
name: 'Run'
}, {
id: 2,
name: 'Garden'
}, {
id: 19,
name: 'Mountain'
}]
One function to get the alphabets between the two:
function genCharArray(charA, charZ) {
var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
for (; i <= j; ++i) {
a.push(String.fromCharCode(i));
}
return a;
};
Then your filter:
app.filter("cfilter", function () {
return function (input, x, y) {
var groups = [];
var letters = genCharArray(x, y);
for (var i = 0; i < input.length; i++) {
for (var x = 0; x < letters.length; x++) {
if (input[i].name.substring(0, 1) == letters[x])
groups.push(input[i]);
}
} return groups;
}
});
And your HTML:
<div ng-repeat="w in myList | cfilter: 'A':'H' | orderBy: 'name'">
<div>{{w.name}}</div>
</div>
create one directive pass an array of letter and range of alphabates you want to disaply.
<dummy-directive data="arrayData" range="A-G"></dummy-directive>
<dummy-directive data="arrayData" range="H-L></dummy-directive>
<dummy-directive data="arrayData" range="M-P"></dummy-directive>
<dummy-directive data="arrayData" range="Q-Z"></dummy-directive>
Now question is that how to implement directive?
we will display sorted data.

Resources