4

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}
];
1
  • I would like to use Jquery to create the new array, i am not sure if map function would help. If it's better with plain javaScript its great too. Commented Sep 4, 2013 at 5:05

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

I just looked up $.map and it mentioned running the array through $.makeArray -- would this be relevant here?
@RUJordan no it is not since the OP has an actual array
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.