Rohan Sandeep
Rohan Sandeep

Reputation: 414

Create new array from an existing array attributes

I am trying to create a new array out of limited values from an existing array. In the example below LargeArray contains many attributes – year, books, gdp and control. Lets say I want to create a new array that would only include year and gdp.

var LargeArray = [
    {year:1234, books:1200, gdp:1200, control:1200}, 
    {year:1235, books:1201, gdp:1200, control:1200}, 
    {year:1236, books:1202, gdp:1200, control:1200}
];

The new array I am trying to get, would look like this:

var NewArray = [
    {year:1234, gdp:1200},
    {year:1235, gdp:1200},
    {year:1236, gdp:1200}
];

Upvotes: 4

Views: 5658

Answers (2)

c.P.u1
c.P.u1

Reputation: 17094

Using Array.prototype.map

var newArray = largeArray.map(function(obj) {
  return { year: obj.year, gdp: obj.gdp };
});

Note: Array.prototype.map is a recent addition. Use the shim from MDN to support older browsers.

jsFiddle Demo

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

use $.map()

var LargeArray = [{year:1234, books:1200, gdp:1200, control:1200}, {year:1235, books:1201, gdp:1200, control:1200}, {year:1236, books:1202, gdp:1200, control:1200}, {year:1237, books:1203, gdp:1200, control:1200}, {year:1238, books:1204, gdp:1200, control:1200}];
var NewArray = $.map(LargeArray, function (value) {
    return {
        year: value.year,
        gdp: value.gdp
    }
})

Demo: Fiddle

Upvotes: 5

Related Questions