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
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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With