I have an array containing objects. Now I want to slice the array to new arrays containing only those objects matching a certain property value.
Ideally the new array names should be created dynamically.
The original array looks like this:
specificSlotButtonArray = [
{slotStarttime:"06:00:00", slotTimespan:1},
{slotStarttime:"09:00:00", slotTimespan:1},
{slotStarttime:"12:00:00", slotTimespan:2},
{slotStarttime:"15:00:00", slotTimespan:2},
{slotStarttime:"18:00:00", slotTimespan:3}
];
The new arrays should look like this:
timespan1 = [
{slotStarttime:"06:00:00", slotTimespan:1},
{slotStarttime:"09:00:00", slotTimespan:1}
]
timespan2 = [
{slotStarttime:"12:00:00", slotTimespan:2},
{slotStarttime:"15:00:00", slotTimespan:2}
]
timespan3 = [
{slotStarttime:"18:00:00", slotTimespan:3}
]
If possible, I want to avoid javascript syntax / functions, which are not supported by IE and some other older browsers.
I already tried to work with reduce()
and slice()
, but did not find a solution.
You can simply achieve your desired outcome using reduce
, as you can produce an object using reduce
, here's an example of how you could do it.
As you can see, it'll check that the relevant property on the object isn't null, if it is, then it's set to an empty array, after this check, it's safe to simply push the relevant values onto the array, like so.
var array = [{
slotStarttime: "06:00:00",
slotTimespan: 1
},
{
slotStarttime: "09:00:00",
slotTimespan: 1
},
{
slotStarttime: "12:00:00",
slotTimespan: 2
},
{
slotStarttime: "15:00:00",
slotTimespan: 2
},
{
slotStarttime: "18:00:00",
slotTimespan: 3
}
];
var newObject = array.reduce(function(obj, value) {
var key = `timespan${value.slotTimespan}`;
if (obj[key] == null) obj[key] = [];
obj[key].push(value);
return obj;
}, {});
console.log(newObject);
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