简体   繁体   中英

Is this the most efficient way to split one array into 2 more?

I'm having a bit of a mental block, but is there a more efficient way of creating 2 new arrays, from values in another array?

Here is my current example and while it works, I feel there may be a more efficient method;

Original Array;

const daily = [
    {event_date: "2019-10-18", listener: 3},
    {event_date: "2019-10-19", listener: 3},
    {event_date: "2019-10-20", listener: 1}
];

What I need to do, is create 2 new arrays, one with the event_date values and the other with the listener values.

I am using map to achieve this like so;

const dailyLabels = daily.map((data) => {
    return data.event_date;
});
const dailyData = daily.map((data) => {
    return data.listener
});

Now I have 2 new arrays that I can use, but it doesn't seem like the best approach. Am I right or am I wrong?

You could use Array.reduce therefore you only iterate over the length of the array once.

 const daily = [ { event_date: "2019-10-18", listener: 3 }, { event_date: "2019-10-19", listener: 3 }, { event_date: "2019-10-20", listener: 1 } ]; const { dailyLabels, dailyData } = daily.reduce( (result, { event_date, listener }) => { result.dailyLabels.push(event_date); result.dailyData.push(listener); return result; }, { dailyLabels: [], dailyData: [] } ); console.log(dailyLabels); console.log(dailyData);

You can use Array.reduce to do that

 daily.reduce((rs, el) => {rs.listeners.push(el.listener); rs.event_dates.push(el.event_date); return rs;}, {event_dates: [], listeners: []})

Just a bit of simplifying...

const dailyLabels = daily.map((data) => data.event_date);
const dailyData = daily.map((data) => data.listener);

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM