Creating and pushing elements in an new array depends on conditions - arrays

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));
}

Related

Typescript - replace value in an array object

Tried two ways to get partial summary within each array object, but failed.
var arr = [
{ "value": 10, "newBalance": 0 },
{ "value": -10, "newBalance": 0 },
{ "value": 15, "newBalance": 0 },
];
let total = 0;
for (let i = 0, l = arr.length; i < l; ++i) {
total = total + arr[i].value;
arr.map( item => { item.newBalance = total; return item; });
// update all newBalance values with the last total value
arr.map(item => item.newBalance != 0 ? { ...item, newBalance: total } : item);
// doesn't update newBalance
}
console.log(arr);
What am I doing wrong here ?
It can be done cleanly in a single loop with reduce. Note this returns a new array, it won't mutate the original. But you can always reassign arr to the new one if you want.
With reduce you can access the current accumulation which is very useful here as you can get the previous rolling value to build on for each item.
const arrayWithSummary = arr.reduce((summary, currentLineItem, index) => {
return [...summary, { ...currentLineItem, newBalance: currentLineItem.value + (summary?.[index - 1]?.newBalance ?? 0)}]
}, [])
The result is in arrayWithSummary.

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 );
}
})

How to initialize an empty array of object with a predefined array?

I am facing lot of issue to initialize an array of object with a predefined array. I am not being able to copy that array to my new array of objects. If anyone knows it then let me know.
admins is basically an array which contains string items like ["hello","hii","sup",....]
var admins = ["hello","hii","sup"];
var obj = [];
for(var i=0; i<admins.length; i++)
{
obj[i].name = admins[i];
}
console.log(obj);
"TypeError: Cannot set property 'name' of undefined"
Use a map:
var newArray = admins.map((admin) => ({ name: admin }));
IMHO: use spread operator:
const admins = ["John", "Doe", "Duck"];
const obj = [...admins].map(
(admin) => ({ name: admin })
);
console.log(obj);
Try out this
var obj = [];
for (var i = 0; i < admins.length; i++) {
let temp = {};
temp["name"] = admins[i];
obj.push(temp);
}
console.log(obj);
You need to define the obj[i] to empty object (obj[i] = {}).
you are trying to access name property of undefined(obj[i] is undefined in your code).
var obj = [];
for(var i=0; i<admins.length; i++)
{
obj[i] = {
name: admins[i]
}
}
console.log(obj);

Angular2 JSON Duplication Deletion

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;
}

Resources