I have a data structure that looks like this:
const carsData = [
{
name: "Cars",
collection: [
{ year: 2011, model: "B", price: 4400 },
{ year: 2015, model: "A", price: 32000 },
{ year: 2016, model: "B", price: 15500 }
]
},
{
name: "Trucks",
collection: [
{ year: 2014, model: "D", price: 18000 },
{ year: 2013, model: "E", price: 5200 }
]
},
{
name: "Convertibles",
collection: [
{ year: 2009, model: "F", price: 20000 },
{ year: 2010, model: "G", price: 8000 },
{ year: 2012, model: "H", price: 12500 },
{ year: 2017, model: "M", price: 80000 }
]
}
];
and want to return a new array let's say const newCarsData(see below) where collection consists of only objects with year higher than 2013, so it will look like this:
const newCarsData = [
{
name: "Cars",
collection:[
{ year: 2015, model: "A", price: 32000 },
{ year: 2016, model: "B", price: 15500 }
]
},
{
name: "Trucks",
collection: [
{ year: 2014, model: "D", price: 18000 }
]
},
{
name: "Convertibles",
collection: [
{ year: 2017, model: "M", price: 80000 }
]
}
];
I tried filter method collection.filter(x => x.year > 2013) inside of for loop, but couldn't make it work. At the end my code looked like this
const newCarsData = getNewData(carsData);
let arr = [];
function getNewData(somedata) {
for (let i = 0; i < somedata.length; i++) {
// console.log(somedata[i].collection);
for (let j = 0; j < somedata[i].collection.length; j++) {
let arr.push(somedata[i].collection[j]);
// console.log(somedata[i].collection[j]);
}
// return somedata[i].collection.filter(x => x.year > 2013);
}
return arr.filter(x => x.year > 2013);
}
where you post a list of your requirements and language of choice and a code monkey churns out code for youlol . nice.