Tim
Tim

Reputation: 911

Using array.map() to find elements from an array of objects

I have an array of objects and I'd like to return an array of all the ids. For example:

const arr = [
    {Locations:[{id:2129, Name: 'testAA'}, {id:3431, Name: 'testAB'}, {id:4373, Name: 'testAC'}]},
    {Locations:[{id:2545, Name: 'testBA'}, {id:3431, Name: 'testBB'}]}
];     

I'd like to return: [2129, 3431, 4373, 2545, 3431]

I've tried to following:

arr.map((value) => {
    let newarray = [];
    return newarray += value['Locations'].map(ID => ID.id);
});

This returns: ["2129,3431,4373", "2545,3431"]

How do I combine those two arrays?

Upvotes: 3

Views: 7883

Answers (6)

Tyler Roper
Tyler Roper

Reputation: 21672

Given that your input and output aren't a 1-to-1 mapping, this doesn't seem like a great use-case for .map(). Instead, I'd consider using .map() only on the inner array, but using .reduce() on the outer.

const arr = [{Locations:[{id:2129, Name: 'testAA'}, {id:3431, Name: 'testAB'}, {id:4373, Name: 'testAC'}]},{Locations:[{id:2545, Name: 'testBA'}, {id:3431, Name: 'testBB'}]}];     

const result = arr.reduce((acc,{Locations}) => [...acc, ...Locations.map(i=>i.id)], []);

console.log(result);

As an alternative, you could use .concat():

const arr = [{Locations:[{id:2129, Name: 'testAA'}, {id:3431, Name: 'testAB'}, {id:4373, Name: 'testAC'}]},{Locations:[{id:2545, Name: 'testBA'}, {id:3431, Name: 'testBB'}]}];     

const result = arr.reduce((acc,{Locations}) => acc.concat(Locations.map(i=>i.id)), []);

console.log(result);

Upvotes: 5

ggorlen
ggorlen

Reputation: 57096

Array#flatMap is the correct tool for this scenario, but if browser compatibility prohibits its use, you can flatten using Array#concat and spread syntax:

const arr = [{Locations:[{id:2129, Name: 'testAA'}, {id:3431, Name: 'testAB'}, {id:4373, Name: 'testAC'}]}, {Locations:[{id:2545, Name: 'testBA'}, {id:3431, Name: 'testBB'}]}];

console.log([].concat(...arr.map(e => e.Locations.map(e => e.id))));

Upvotes: 0

jimboweb
jimboweb

Reputation: 4542

You don't have two arrays there, you have an array of two concatenated strings. You don't need the newarray[] at all; .map() returns a new array for you.

When you get that you can combine it with a reduce().

What you want will look like this:

arr
    .map((value) => value['Locations']
        .map(ID => ID.id))
    .reduce((accum, arr)=>accum.concat(arr));

Upvotes: 0

Mamun
Mamun

Reputation: 68913

You can try with Array.prototype.flatMap():

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

and Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

const arr = [
    {Locations:[{id:2129, Name: 'testAA'}, {id:3431, Name: 'testAB'}, {id:4373, Name: 'testAC'}]},
    {Locations:[{id:2545, Name: 'testBA'}, {id:3431, Name: 'testBB'}]}
];
const newarray = arr.flatMap(i => i.Locations.map(j => j.id));
console.log(newarray);

Upvotes: 2

MillerC
MillerC

Reputation: 731

I like Tyler Roppers answer

concat the two arrays https://www.w3schools.com/jsref/jsref_concat_array.asp

haven't tested by maybe return newarray.concat(value['Locations'].map(ID => ID.id));

Could also run something like this which might be a bit cleaner.

arr.map((value) => {
    let newArray = [];
    Locations.map((location) => {
        return newArray.push(location.id)
    });
    if(newArray.length) return newArray;
    return null;
}

Upvotes: 0

iPhoenix
iPhoenix

Reputation: 737

Try using

arr.map((value) => {
    let newarray = [];
    return newarray += value['Locations'].map(ID => ID.id);
}).join(',').split(',').map((value) => parseInt(value, 10));

Here's the "chain of events": ["2129,3431,4373", "2545,3431"] -> "2129,3431,4373,2545,3431" -> ["2129","3431","4373","2545","3431"] -> [2129, 3431, 4373, 2545, 3431]

Upvotes: 1

Related Questions