1

How can I access the data in y "column" in data1 array and push the data to a new array data2?

var data1 = [
  {x:1, y:3, s:0.15},
  {x:2, y:2.7, s:0.1},
  {x:0.7, y:3, s:0.15},
  {x:2.3, y:2.9, s:0.12}
];

var data2 = [3, 2.7, 3, 2.9]

This is what I tried:

var data2 = [];
for (var j = 0; j < data1.length; j++) {
  if ( ) {
    data2.push( );
  };
};

I am not a javascript user. Appreciate if anyone help to finish it!

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
newb
  • 53
  • 6
  • To mkae your code work, you should just have to remove the `if` statement and use `data2.push(data1[j].y)`. You might want to read http://eloquentjavascript.net/04_data.html . – Felix Kling Jan 13 '16 at 16:45

1 Answers1

1

You can use .map like this

var data1 = [
  {x: 1, y: 3, s: 0.15},
  {x: 2, y: 2.7, s: 0.1},
  {x: 0.7, y: 3, s: 0.15},
  {x: 2.3, y: 2.9, s: 0.12}          
];

var data2 = data1.map(function (e) {
  return e.y;
})

console.log(data2);

or modify your version like this

var data1 = [
  {x: 1, y: 3, s: 0.15},
  {x: 2, y: 2.7, s: 0.1},
  {x: 0.7, y: 3, s: 0.15},
  {x: 2.3, y: 2.9, s: 0.12}          
];

var data2 = [];
for (var j = 0; j < data1.length; j++) {
  data2.push(data1[j].y);
};

console.log(data2);
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144