Insert data into array with specific index in Angular 4 - arrays

Why that is not working in TypeScript?
Example:
views: any[] = [360001232825, 360001232845, 360001217389];
MyArray:any[];
for (var i = 0; i < this.views.length; i++) {
this.subscription = this.dataService.getMyData(this.views[i]).subscribe(data => {
this.myArray[this.views[i]]=data;
});
}
When I use .push data is inserted into my array but I want to use a specific index.

If you want to insert an Item use splice. But obviously you want to use a Map or an object.
let ar = ["one", "two", "four", "five"];
console.log("Before:\n" + ar);
ar.splice(2, 0, "three");
console.log("After:\n" + ar);
Maybe this will help:
let namedIndexes = [1564789, 234895, 249846];
let map = {};
let data = "this is your data arg";
namedIndexes.forEach((v, i, ar) => {
map[v] = data + " data at " + v;
});
console.log(map);
'map' is like your this.myArray, 'data' is your parameter and 'namedIndexes' is your view array. I hope the code explains itself.

Related

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

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

Retrieve the Object values and assign it to Another one Object in ReactJS

I have to retrieve an object and assign it to another one. But in the new object, always the last item only stored.
I tried object.entries keys method but nothing worked.
code : https://codesandbox.io/s/k3p7j07x8o
let subject = {};
const obj = { a: 5, b: 4, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`);
//console.log(subject); // Here itself it's printing the last element
subject.value = key;
subject.text = value;
console.log(subject.value + subject.text); // This showing the correct element
console.log(subject); // This one showing the last elements
}
You can use this syntax:
let subject = Object.assign({}, obj}
console.log(subject)
or
let subject = {};
Object.assign(subject, obj);
console.log(subject)

How to apply search filter on 2 different arrays in Ionic 2?

I have applied search filter on a array using this code in my listproduct.ts
if (val && val.trim() != '') {
this.names = this.names.filter((names) => {
return (names.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
Note that this filter is applied on names array. I wish this filter should also work on catg and pservice named arrays too.
How can I achieve filter result on multiple arrays?
You can create another bigArray which is the concatenation of your three arrays using js concat function :
var bigArray = this.names.concat(this.catg, this.pservice);
and call your filter on that bigArray.
var val = "test";
this.names = ["abc", "test123", "test"];
this.catg = ["qsd", "azetest"];
this.pservice = ["another test !", "tss"];
this.bigArray = this.names.concat(this.catg, this.pservice);
// here, bigArray contains all values of the three arrays (abc,test123,test,qsd,azetest,another test !,tss)
if (val && val.trim() != '') {
this.bigArray = this.bigArray.filter((names) => {
return (names.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
// here, bigArray contains only filtered values of the three arrays (test123,test,azetest,another test !)
Here is a working Plunker
If you need to keep them as separate arrays, and cannot concat them, you could do something like this:
let names = ["Andy", "Alex", "Corbyn", "Eric" ];
let catg = ["Adventure", "Action", "Comedy", "SciFi"];
let pservice = ["Example", "Service", "Allo"]
let val = "a";
[names, catg, pservice] = [names, catg, pservice].map(array => {
return array.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
});
console.log(names);
console.log(catg);
console.log(pservice);

Append elements form JSON response to multidimensional array

I am using Alamofire and SwiftyJSON.
Code:
var array = Array<Array<String>>()
Alamofire.request(.GET, url, parameters: ["postType": "live"], encoding: ParameterEncoding.URL).responseJSON { (_, _, result) in
switch result {
case .Success(let data):
let json = JSON(data)
for(_,subJSON):(String, JSON) in json["Info"] {
let Tag = subJSON["Tag"].string!
let Location = subJSON["Location"].string!
array.append(Array(count: 4, repeatedValue: concertTag))
}
case .Failure(_, let error):
print("Request failed with error: \(error)")
}
}
I want to create an array multidimensional. And add JSON variables to it for after pass the array to TableView.
So basically i need "array" to be like:
[[Tag1; Location1],[Tag2, Location2], .... ]
How can I do this? any ideas?
Thank you
You just would have to replace
array.append(Array(count: 4, repeatedValue: concertTag))
with
array.append([Tag, Location])
And you would get the data back like this for example:
for arr in array {
print("tag: " + arr[0])
print("loc: " + arr[1])
}
But I would suggest another approach: using tuples.
First let's create a type result because it's convenient:
typealias TagAndLocation = (tag: String, location: String)
Then prepare an empty array of results:
var resultTuples = [TagAndLocation]()
Fill the array of tuples in the loop:
for (_, subJSON) in json {
let Tag = subJSON["Tag"].string!
let Location = subJSON["Location"].string!
let tagloc = (tag: Tag, location: Location)
resultTuples.append(tagloc)
}
Then you can access your data in two ways:
for (tag, loc) in resultTuples {
print("tag: " + tag)
print("loc: " + loc)
}
for result in resultTuples {
print("tag: " + result.tag)
print("loc: " + result.location)
}
Note: your variables names should begin with a lowercase letter. Beginning with uppercase is usually for classes, types, protocols and such.

Resources