javascriptarraysobject

Javascript Object, return a new array with the indexes that match the object


I have the following array containing object that holds details of a league venue and code.

I also have another array with just league codes.

I want to return a new array of the indexes of the league.venue object in the order of the league codes array.

For example the new array in this case would be - [4,5,0,3,2].

I am not sure if it is best to .map or .filter but I don't want to use push().

league  = {};
league.venue  = [];
league.venue[0] = {};
league.venue[0].code  = 1000;
league.venue[0].team  = "Arsenal";

league.venue[1] = {};
league.venue[1].code  = 1001;
league.venue[1].team  = "Spurs";

league.venue[2] = {};
league.venue[2].code  = 1002;
league.venue[2].team  = "Liverpool";

league.venue[3] = {};
league.venue[3].code  = 1003;
league.venue[3].team  = "Manchester City";

league.venue[4] = {};
league.venue[4].code  = 1004;
league.venue[4].team  = "Manchester United";

league.venue[5] = {};
league.venue[5].code  = 1005;
league.venue[5].team  = "Everton";

league.code = [1004, 1005, 1000, 1003, 1002]


Solution

  • A different approach by having an object and a single loop for the data.

    const
        league = { venue: [{ code: 1000, team: "Arsenal" }, { code: 1001, team: "Spurs" }, { code: 1002, team: "Liverpool" }, { code: 1003, team: "Manchester City" }, { code: 1004, team: "Manchester United"}, { code: 1005, team: "Everton" }], code: [1004, 1005, 1000, 1003, 1002] },
        targets = Object.fromEntries(Object
            .entries(league.code)
            .map(([k, v]) => [v, k])
        ),
        result = league.venue.reduce(
            (r, { code }, i) => r.with(targets[code], i),
            Array(league.code.length)
        );
    
    console.log(result);