Leon Gaban
Leon Gaban

Reputation: 39028

Create one array from 2 Arrays with keys x & y

I have 2 Arrays xDates and yMentions

xDates

[1453766400000, 1453852800000, 1453939200000...

yMentions

[5160, 5240, 7090...

Goal is an Array like so:

[
    {
       x: 1453766400000,
       y: 5160
    },
    ...
]

Trying to use Ramda Zip thought zipObj would be what I need, but the following produces just 1 object:

R.zipObj(['x', 'x', 'x'], [1, 2, 3]); => {"x": 3}

Figured perhaps I run R.zipObj on the x then the y arrays, then zip them together then set that as the Array for mentionsPointsArray below:

const createMentionPoints = (frequencyPoints, termsData) => {
    const yMentions = termsData.mentions;
    const propX = R.prop('x');
    const xPointsFromFrequency = R.map(propX, frequencyPoints);
    console.log('xDates', xPointsFromFrequency)
    console.log('yMentions', yMentions)
    const mentionsPointsArray = []
    return frequencyPoints;
};

Upvotes: 1

Views: 99

Answers (3)

jgr0
jgr0

Reputation: 727

I think the cleanest point-free version would be:

const data1 = ['a', 'b', 'c']
const data2 = [1, 2, 3]

R.zipWith(R.objOf, data1, data2)

Please have a look at a working REPL here

Upvotes: 1

Leon Gaban
Leon Gaban

Reputation: 39028

The ramda solution http://ramdajs.com/docs/#zipWith

var createPoints = (x, y) => {
  return { x: x, y: y }
};

R.zipWith(createPoints, [1, 2, 3], ['a', 'b', 'c']);

// returns: [{"x": 1, "y": "a"}, {"x": 2, "y": "b"}, {"x": 3, "y": "c"}]

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You should use Array#map function.

The map() method creates a new array with the results of calling a provided function on every element in this array.The provided function is a callback.

The elements from the result array are objects, like this: {"x":item, "y":yMentions[i]}.

var xDates=[1453766400000, 1453852800000, 1453939200000];
var yMentions=[5160, 5240, 7090];
console.log(xDates.map(function(elem,i){
    return {"x":elem,"y":yMentions[i]}
}));

Upvotes: 2

Related Questions