Split an array of objects in to two, based on a value within the object

I have been trying (and struggling) to figure out how I am able to split an array of objects, based on a key value pair

Long story short, I have a list of stations that a train is calling at, and need to separate the stations previous calling points, and the stations future calling points.

The data i’m working with looks like this:

[{station_code: "SOC", station_name: "Southend Central" },
{station_code: "WCF", station_name: "Westcliff On Sea" },
{station_code: "CHW", station_name: "Chalkwell" },
{station_code: "LES", station_name: "Leigh On Sea" },
{station_code: "BEF", station_name: "Benfleet" },
{station_code: "PSE", station_name: "Pitsea" },
{station_code: "BSO", station_name: "Basildon" }]

I’d like to have two new arrays that are split at, for example Leigh On Sea.. like this:

previous stops:

[{station_code: "SOC", station_name: "Southend Central" },
{station_code: "WCF", station_name: "Westcliff On Sea" },
{station_code: "CHW", station_name: "Chalkwell" }]

subsequent stops:

[{station_code: "BEF", station_name: "Benfleet" },
{station_code: "PSE", station_name: "Pitsea" },
{station_code: "BSO", station_name: "Basildon" }]

it would also help to potentially return the current station (leigh on sea) as well as a separate array with the object in it if possible…

I have come across this, however i cant think how i can adjust this to look in to the object to find the station name:

const getAllAfter = (current) => {
    var myArr = new Array("alpha", "beta", "gamma", "delta");
    var i = myArr.indexOf(current);
    return i > -1 ? myArr.slice(0, i) : [];
};

Thanks in advance! 🙂

29 thoughts on “Split an array of objects in to two, based on a value within the object”

  1. 198272 877209Cheapest speeches and toasts, as nicely as toasts. probably are developed building your personal at the party and will likely be most likely to turn into witty, humorous so new even. best man toast 300243

    Reply

Leave a Comment