Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Split array of objects into seperate arrays with dynamic names depending on property value

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.

like image 253
Gardinero Avatar asked Jan 02 '19 15:01

Gardinero


1 Answers

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);
like image 55
JO3-W3B-D3V Avatar answered Oct 14 '22 17:10

JO3-W3B-D3V