Jamgreen
Jamgreen

Reputation: 11059

Map values in array of objects

I have an array

const nodes = [
    { layer: '0' },
    { layer: 'input' },
    { layer: '0' },
    { layer: 'output' },
    { layer: '1' }
};

I want to keep the array, but all the layer values should be changed.

The input layer should have value 1, all the numeric values should be increased by 2 and the output layer should have the new highest numeric value plus 1. All the values should be numbers instead of strings.

So the new array will be

const nodes = [
    { layer: 2 },
    { layer: 1 },
    { layer: 2 },
    { layer: 4 },
    { layer: 3 }
};

I have accomplished this with

const nodes = [
    { layer: '0' },
    { layer: 'input' },
    { layer: '0' },
    { layer: 'output' },
    { layer: '1' }
};

const output = Math.max.apply(Math, nodes.map((node) => Number.parseInt(node.layer, 10) || 0)) + 3;

nodes.map((node) => {
  layer: neuron.layer === 'input' ? 1 : (neuron.layer === 'output' ? output : Number.parseInt(neuron.layer, 10) + 2)
})

It seems to work, but the code is really ugly.

I wonder if it can be done more neat than this.

Upvotes: 0

Views: 743

Answers (2)

trincot
trincot

Reputation: 351278

What about this:

const nodes = [
    { layer: '0' },
    { layer: 'input' },
    { layer: '0' },
    { layer: 'output' },
    { layer: '1' }
];

nodes.filter( o => o.layer === 'output' )[0].layer = 
    1 + nodes.reduce( (max, node) => Math.max(max, 
        node.layer = +(node.layer === 'input') || +node.layer+2 || 0), 0);

console.log(nodes);

For those wondering about const here: the constant nature only protects the variable from a reassignment; but the objects stored within the array can be freely mutated.

Upvotes: 1

Redu
Redu

Reputation: 26201

This might be one way of doing this job;

var nodes = [
    { layer: '0' },
    { layer: 'input' },
    { layer: '0' },
    { layer: 'output' },
    { layer: '1' }
],
result = nodes.map(n => isNaN(+n.layer) ? n.layer === "input" ? {layer:1}
                                                              : {layer: n.layer}
                                        : n.layer = {layer:+n.layer + 2});
result.find(o => o.layer === "output").layer = result.filter(f => !isNaN(f.layer))
                                                     .reduce((p,c) => p.layer > c.layer ? p : c)
                                                     .layer + 1;
console.log(result);

Upvotes: 1

Related Questions