1

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.

4
  • How are you testing if this works or not? Commented Jun 18, 2018 at 15:32
  • where is defined this.myArray I think that you are trying to do a key map. Commented Jun 18, 2018 at 15:34
  • initizlize the array: MyArray:any[]=[]; Anyway, e.g. this.view[0]=360001232825. Are you sure you want to say this.MyArray[360001232825]=data? it's possible you want to say MyArray:any={} //an object Commented Jun 18, 2018 at 16:07
  • Thanks guys for your response ! Commented Jun 19, 2018 at 8:41

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That what i want thanks ! And if i want to initialize my array with a specific index how can I do that ? { "Monday": 2,"Sunday":5}
yes that would work. Then you can do myArray["Monday"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.