Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new array with two columns from old array

I have an array as follows:

items = [
{"year": 2010, "month": 11, "day":23}
{"year": 2009, "month": 10, "day":15}
{"year": 2009, "month": 10, "day":10} //added after my edit below
]

I would like to create a new array with only 2 of the columns like this:

newArarry = [
{"year": 2010, "month": 11}
{"year": 2009, "month": 10}
]

Right now Im trying with .map() and its not working:

const newArray = [];
newArray.map({
    year: items.year,
    month: items.month
});

EDIT

After following one of the answers below, I realized I forgot to mention that I would also need to filter the result to be only unique rows. Now that I am only selecting the year and month columns, I am getting multiple duplicate rows

like image 685
Mennyg Avatar asked May 21 '19 08:05

Mennyg


People also ask

What method would create new array that will have the same length of the original array?

Array.prototype.map() prototype. map() creates a new array by applying the provided transformation to each element of the original array. The result is an array with the same length as the original array and elements transformed based on the provided function.

How do you add a new array to an existing array?

To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array. The method changes the contents of the original array.

What is a nested array?

Nested Array in JavaScript is defined as Array (Outer array) within another array (inner array). An Array can have one or more inner Arrays. These nested array (inner arrays) are under the scope of outer array means we can access these inner array elements based on outer array object name.

Can you have an array of arrays in JavaScript?

JavaScript does not provide the multidimensional array natively. However, you can create a multidimensional array by defining an array of elements, where each element is also another array. For this reason, we can say that a JavaScript multidimensional array is an array of arrays.


1 Answers

Array's .map() method accepts a callback whose returned value will be used to construct new array. Mistakenly you are passing it an object instead of a function. To fix this you can use .map() with some Object Destructuring:

const items = [
  {"year": 2010, "month": 11, "day":23},
  {"year": 2009, "month": 10, "day":15}
];

const result = items.map(({ year, month }) => ({year, month}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 123
Mohammad Usman Avatar answered Nov 15 '22 19:11

Mohammad Usman