Angular2 JSON Duplication Deletion - arrays

I am working with a large JSON file holding information about instructors at my school. I want to be able to pull all the teachers names from this list so I can then put them into Firebase. However, whenever I loop over my JSON file and try to filter out all the duplicate teacher names I still end up with duplicates even when I try to do a second round of deletion. The JSON looks like this:
{
"Id": "1",
…
"Instructor": "name1, name2, name3",
…
},
{
"Id": "2",
…
"Instructor": "name1",
…
},
{
"Id": "3",
…
"Instructor": "name1, name2",
…
}
As seen above sometimes there is just one name, other times there are multiple. I handle this though in my logic but no matter what I still end up with duplicates. If anyone can help me come up with a way to solve this it would be greatly appreciated. I'll add my code that I have already below.
public remove_duplicates(arr: any[]): any[] {
let output: any[] = [];
for (let i = 0; i < arr.length; i++) {
let instruc: any[] = arr[i].Instructor.split(',');
for (let j = 0; j < instruc.length; j++) {
let push: boolean = true;
arr[i].Instructor = instruc[j];
for (let k = 0; k < output.length; k++) {
let i1: string = output[k].Instructor;
let i2: string = arr[i].Instructor;
if (i1.trim().localeCompare(i2.trim()) == 0) {
push = false;
}
}
if (push)
output.push(arr[i]);
}
}
console.log(output.length);
for (let k = 0; k < output.length; k++) {
for (let i = k + 1; i < output.length; i++) {
if (new String(output[i].Instructor).valueOf().trim()
=== new String(output[k].Instructor).valueOf().trim()) {
output.splice(i, 1);
}
}
}
for (let k = 0; k < output.length; k++) {
console.log(output[k].Instructor);
}
console.log(output.length);
return arr;
}
ngOnInit() {
this.http.get('courses.json').take(1)
.map((res: Response) => res.json())
.subscribe(
data => {
this.list = data;
},
err => console.log(err),
() => this.remove_duplicates(this.list)
);
}

There isn't anything specific to Angular 2 that you're trying to do here. This is just vanilla JS.
Try something like this:
public remove_duplicates(arr) {
let seen = {};
let uniqueInstructorNames = [];
arr.forEach(function(item) {
let instructorNames = item.Instructor.split(',');
Array.prototype.push.apply(uniqueInstructorNames, instructorNames.filter( name => {
return seen.hasOwnProperty(item) ? false : (seen[item] = true);
}));
});
return uniqueInstructorNames;
}

Related

Populate an array of array of objects

I must populate an array of array of objects to get something like this:
let dataObj = [
[
{ content: "test1"},
{ content: "test2"},
{ content: "test3"}
],
[
{ content: "test4"},
{ content: "test5"},
{ content: "test6"}
]
]
I start from an array of arrays like this:
data = [["test1", "test2", "test3"], ["test4", "test5", "test6"]]
I tried with:
let dataObj = <any>[[{ }]];
for (let i = 0; i < data.length; i++) {
for (let j=0; j < data[i].length; j++) {
dataObj[i][j].content = data[i][j];
}
}
but after populating the first ([0][0]) it stops and the error is an
uncaught in promise...
(I work in Angular-TypeScript)
I tried also with:
dataObj.push(i,j,{content: data[i][j]});
It gets a result but it's completely wrong.
Add an array into the root array.
Add an object into the nested array.
let dataObj: { content: any;[key: string]: any }[][] = [];
for (let i = 0; i < data.length; i++) {
dataObj.push([]);
for (let j = 0; j < data[i].length; j++) {
dataObj[i].push({ content: data[i][j] })
}
}
Alternatively, you can work with .map().
let dataObj: { content: any;[key: string]: any }[][] = [];
dataObj = data.map(x =>
x.map(y => {
return { content: y };
})
);
Sample TypeScript Playground

Combine arrays and add flag to it if matches the ID

I have two arrays that are identical in structure.
let TaskArray=[
{"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3"},
{"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3"},
{"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3"},
{"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3"},
{"TaskID:"167","TaskName":"task5","TaskGroup":"group","UserID":"3"},
{"TaskID:"166","TaskName":"task6","TaskGroup":"group","UserID":"3"},
{"TaskID:"165","TaskName":"task7","TaskGroup":"group","UserID":"3"},
{"TaskID:"164","TaskName":"task8","TaskGroup":"group","UserID":"3"},
{"TaskID:"163","TaskName":"task9","TaskGroup":"group","UserID":"3"},
{"TaskID:"162","TaskName":"task10","TaskGroup":"group","UserID":"3"}
]
let TaskDetailsArray = [
{"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3"},
{"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3"},
{"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3"},
{"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3"},
]
I need to compare the two arrays and set the flag isAssigned to true if an item from the second array is found by id in the first array, and false otherwise.
matcheArray = [
{"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"167","TaskName":"task5","TaskGroup":"group","UserID":"3"},
{"TaskID:"166","TaskName":"task6","TaskGroup":"group","UserID":"3"},
{"TaskID:"165","TaskName":"task7","TaskGroup":"group","UserID":"3"},
{"TaskID:"164","TaskName":"task8","TaskGroup":"group","UserID":"3"},
{"TaskID:"163","TaskName":"task9","TaskGroup":"group","UserID":"3"},
{"TaskID:"162","TaskName":"task10","TaskGroup":"group","UserID":"3"}
]
The code below works ok, but I'm not sure whether there is a better way to accomplish it. Please suggest.
for (var i = 0; i < TaskArray.length; i++) {
for (var k = 0; k < this.TaskDetailsArray.length; k++) {
if (TaskArray[i].TaskID == this.TaskDetailsArray[k].TaskID) {
if (!this.TaskDetailsArray[k].isAssigned) {
this.TaskDetailsArray[k].isAssigned = true;
};
}
}
const comparedArray = taskArray.map(item => {
return {
...item,
isAssigned: TaskDetailsArray.some(secondItem => secondItem.TaskId === item.TaskId );
}
})

simple for loop error from edabit for loop returning undefined

I don't know what is wrong with my for loop in javascript. Can someone please point out my mistake?
function isFourLetters(arr) {
let newArray = [];
for (let i = 0; i < arr.length; i++){
if (arr[i].length === 4){
newArray.push(arr[i]);
}
}
}
I think you were just missing return newArray; in your function.
Here's a runnable example of your code with return newArray; added inside the function:
function isFourLetters(arr) {
let newArray = [];
for (let i = 0; i < arr.length; i++){
if (arr[i].length === 4){
newArray.push(arr[i]);
}
}
return newArray; // This is the value that the function returns when called
}
let exampleArray1 = ["abc", "abcd", "abcde", "bcde"];
let exampleArray2 = ["wxy", "wxyz", "xyz", "test"];
console.log(isFourLetters(exampleArray1));
console.log(isFourLetters(exampleArray2));

Creating and pushing elements in an new array depends on conditions

My Data Array
data:[
0:{
id:1 ,.....
competetion:[
0:{
id: 1....,
match:[
0:{id: 1 ......},
1:{same}
.
.
]
1:{same}]},
2:{same}
.
.
]
},
1:{same},
2:{same}
.
.
.
]
For data[] i able to create a new array(sportarr[]) with pushing elements but i want to create for the same as competetion[] and match[] in the same array sportarr[]
If there any other way to do it please Help me...
My Code: Here i am looping it:
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const arrlength = response.data.length;
for (let i = 0; i < arrlength; i++) {
this.sportarr.push({ // I declared a new array where i want to push the element
id: i,
value: false
});
}
if you want your own content based on the mapping what I will suggest is that first iterate through the array then map each match and competetion and write your own logic inside the map
const arrlength = data.length;
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = data[i].competetion.map( (val, index) => {
#write your own logic to produce the required outcome
return {
id: index,
value: false
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
i Appriciate Pathikrit Sanyal and Fahd Lihidheb For the ansers
Here Is my Change according to Pathikrit Sanyal
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = response.data[i].competetion.map((val, index) => {
let match = [];
match = val.match.map((value, indx) => {
return {
id: indx,
value: false
};
});
return {
id: index,
value: false,
match
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
}
Now i am getting what i wanted
i am not sure if you are trying to create an array for each nasted array (competetion and match) or not, but here you go
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const competetionList = // Array of competetions
[].concat.apply([], this.sportsSidebar.map(item => item.competetion));
const matchList = // Array of matchs
[].concat.apply([], competetionList .map(item => item.match));
}

Compare or filter values from two Json arrays in typescript

I am facing the problem of comparing arrays and filtering the data rows.
I want to filter the data from array1 which is not included in array2 list.
But, I think My logic was wrong with nested array. Could you please help me?
Here is my sample code:
let array1=[{"cblSchKey":693698,"projCode":"11-1115","cblTagNo":"571_GE001-E"},{"cblSchKey":734106,"projCode":"11-1115","cblTagNo":"4000-JB01/4054M1"},{"cblSchKey":725484,"projCode":"11-1115", "cblTagNo": "571_GE001- RC1"},{"cblSchKey":693700,"projCode":"11-1115", "cblTagNo": "571_GE001-S"}];
let array2=[{ "projCode": "11-1115","pullDate": "2019-09-15", "cablePullDtl": [{"cblSchKey": 693698, "remarks": null,"remarks2": "test"}]
},{"projCode": "11-1115","pullDate": "2019-10-01","cablePullDtl":[{"cblSchKey":734106, "remarks": null,"remarks2": "",}]}];
let array3=[]; let array4=[];
for (var j=0; j<array1.length; j++){
for(var k=0; k<array2.length; k++){
let PullDtl =[];
PullDtl = array2[k].cablePullDtl;
for(var i=0; i<PullDtl .length; i++){
if(array1[j].cblSchKey == PullDtl [i].cblSchKey){
array3.push(array1[j]);
}else {
array4.push(array1[j]);
}
}
}
}
console.log("InValid"+JSON.stringify(array3));
console.log("Valid"+JSON.stringify(array4));
I want to get 2 arrays as below after filtered.
array3=[{"cblSchKey":693698,"projCode":"11-1115","cblTagNo":"571_GE001-E"},{"cblSchKey":734106,"projCode":"11-1115","cblTagNo":"4000-JB01/4054M1"}];
array4=[{"cblSchKey":725484,"projCode":"11-1115", "cblTagNo": "571_GE001- RC1"},"cblSchKey":693700,"projCode":"11-1115", "cblTagNo": "571_GE001-S"}];
let array3 = [];
let array4 = [];
array1.forEach(i => {
let a = array2.find(i2 => i2.cablePullDtl.find(c => c.cblSchKey === i.cblSchKey));
if (a === undefined) {
array4.push(i);
} else {
array3.push(i);
}
});

Resources