[Solved] JavaScript Split array into multiple arrays inside [duplicate]


You could take an array of the wanted ids and an object which stores the index for the result set for a same group.

var data = [{ candidateConfigId: "1", value: "199128700790" }, { candidateConfigId: "2", value: "Yujith" }, { candidateConfigId: "3", value: "Male" }, { candidateConfigId: "4", value: "SE" }, { candidateConfigId: "5", value: "Colombo5" }, { candidateConfigId: "1", value: "199128700792" }, { candidateConfigId: "2", value: "Yujith2" }, { candidateConfigId: "3", value: "Male" }, { candidateConfigId: "4", value: "SE" }, { candidateConfigId: "5", value: "Colombo3" }, { candidateConfigId: "1", value: "199128700793" }, { candidateConfigId: "2", value: "Yujith3" }, { candidateConfigId: "3", value: "Male" }, { candidateConfigId: "4", value: "SE" }, { candidateConfigId: "5", value: "Colombo2" }],
    ids = ['1', '2', '3', '4', '5'],
    result = data
        .reduce((r, o) => {
            let index = r.indices[o.candidateConfigId]++;
            r.data[index] = r.data[index] || [];
            r.data[index].push(o);
            return r;
        }, { indices: Object.fromEntries(ids.map(k => [k, 0])), data: [] })
        .data;

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

solved JavaScript Split array into multiple arrays inside [duplicate]