jgr0 jgr0 - 1 month ago 7
Javascript Question

Functional javascript rearrange array index according to some mapping

I have an index mapping like so:

var idxMapping = {
abc: 1,
foo: 2,
bar: 0
};


And an array of objects :

var data = [{
id: 'abc',
info1: 'random info 1',
info2: 'random info 2',
}, {
id: 'foo',
info1: 'random info 1',
info2: 'random info 2',
}]


Using functional programming paradigms, how can I create a new array so that the data gets transformed according to the index specified in the idxMapping.

The result should look something like:

[
null,
{
id: 'abc',
info1: 'random abc info 1',
info2: 'random abc info 2'
},
{
id: 'foo',
info1: 'random foo info 1',
info2: 'random foo info 2'
}
]


The first element is null because the data array does not contain any data that mapped to index 0 (i.e No bar Object in this example).

This is how I implemented using forEach loops :

var result = [];

for (var key in idxMapping) {
result.append(null);
}

data.forEach(function(item) {
result[idxMapping[item.id]] = item;
});


I need a solution strictly following functional programming paradigms.

Answer

There is one of possible approaches in functional programming style:

var idxMapping = {
    abc: 1,
    foo: 2,
    bar: 0
};
var data = [{
    id: 'abc',
    info1: 'random info 1',
    info2: 'random info 2',
}, {
    id: 'foo',
    info1: 'random info 1',
    info2: 'random info 2',
}]

Object.keys(idxMapping)
.sort((fstKey, scndKey) => idxMapping[fstKey] - idxMapping[scndKey])
.map(key => data.find(el => el.id === key))
.map(el => el === undefined ? null : el)