0

Hi!
I'm a beginner in Angular, and haven't really found anything for this, so if you can help me...please.
Here's an array

firstarray[] = [{id:1,name:abc},{id:2,name:cba},{id:3,name:asd}]  

What I'd like to do is:
First: I have an index, for example indexNum = 1;
Then I want a new array with firstarray's index items, the index is 1, so these would be id:2 and name:cba.

indexItems[] = {2,cba}

Secondly:
I want to make two new arrays from the firstarray one stores only the ids and the other stores only the names.

id_array[] = {1,2,3}  

name_array[] = {abc,cba,asd}
1
  • Note that none of this really is angular- or typescript-specific. This is more general, plain javascript. Commented Jul 5, 2018 at 17:54

2 Answers 2

1

For the first task, you should just use the index of the first array in creating the second.

var indexItems = [firstArray[index]];

I'm not sure why you'd need to build an array containing just one item though, since it'd be a little easier to work with the item if it weren't wrapped in the array, such as:

var indexItem = firstArray[index];

For the second task, the map function is convenient for mapping one array to a transformed array. Note also that you probably need to quote your strings in your array. (I am assuming they're not variable names.)

// [{id:1,name:'abc'},{id:2,name:'cba'},{id:3,name:'asd'}]  
var nameArray = firstArray.map(item => item.name);
// ['abc', 'cba', 'asd']
var idArray = firstArray.map(item => item.id);
// [ 1, 2, 3 ]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, thank you :) I get all of the data here jsonplaceholder.typicode.com/users
0

FIRST

indexItems= Object.values(firstarray[1])

SECOND

valsArr1=[]
valsArr2=[]
firstarray.forEach(item=>{
valsArr1.push(item['id']);
valsArr2.push(item['name']);
})

Comments

Your Answer

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