Javascript: Split array of objects into seperate arrays with dynamic names depending on property value
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);
How to split an Array of Objects into another Arrays based on their values?
Although it's possible to create global variables with dynamic names, it's not possible to create non-global variables with dynamic names, and the global environment is already sufficiently crowded that creating a bunch of new globals is not best practice.
Instead, use a Map
:
const playerArrays = new Map();
for (const entry of database) {
const key = `player${entry.player}`;
const array = playerArrays.get(key);
if (!array ) {
// Haven't seen this one yet, add a new array
playerArrays.set(key, [entry]);
} else {
// We have the array, add to it
array.push(entry);
}
}
Then you get an individual array by using playerArrays.get("player1")
and such.
Live Example:
var database = [{
player: 1,
level: 1,
score: 20
},
{
player: 2,
level: 1,
score: 25
},
{
player: 3,
level: 1,
score: 7
},
{
player: 1,
level: 2,
score: 25
},
{
player: 2,
level: 2,
score: 7
}
];
const playerArrays = new Map();
for (const entry of database) {
const key = `player${entry.player}`;
const array = playerArrays.get(key);
if (!array ) {
// Haven't seen this one yet, add a new array
playerArrays.set(key, [entry]);
} else {
// We have the array, add to it
array.push(entry);
}
}
console.log("player1:", playerArrays.get("player1"));
.as-console-wrapper {
max-height: 100% !important;
}
Split array with objects to multiple arrays based on unique combination
Another short Array.prototype.reduce()
approach:
var dataset = [ {time: "t1", locA: "a1", locB: "b1", value: "v1"}, {time: "t1", locA: "a1", locB: "b2", value: "v2"}, {time: "t1", locA: "a2", locB: "b1", value: "v3"}, {time: "t1", locA: "a2", locB: "b2", value: "v4"}, {time: "t2", locA: "a1", locB: "b1", value: "v5"}, {time: "t2", locA: "a1", locB: "b2", value: "v6"}, {time: "t2", locA: "a2", locB: "b1", value: "v7"}, {time: "t2", locA: "a2", locB: "b2", value: "v8"}];
var result = dataset.reduce(function(r, o){ var k = o.locA + o.locB; // unique `loc` key if (r[k] || (r[k]=[])) r[k].push({loc:k, time: o.time, value: o.value}); return r;}, {});
console.log(result);
How to split array dynamically based on single value in JavaScript Node.js
You could use an object with the grouped items. It works for any tags and allows a list of all tags with Object.keys(grouped)
, if required.
var dataStuff = [{ Name: 'Apple', Tag: 'Fruit', Price: '2,5' }, { Name: 'Bike', Tag: 'Sport', Price: '150' }, { Name: 'Kiwi', Tag: 'Fruit', Price: '1,5' }, { Name: 'Knife', Tag: 'Kitchen', Price: '8' }, { Name: 'Fork', Tag: 'Kitchen', Price: '7' }], grouped = Object.create(null);
dataStuff.forEach(function (a) { grouped[a.Tag] = grouped[a.Tag] || []; grouped[a.Tag].push(a);});
document.write(Object.keys(grouped));document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
Split array into chunk of different size on the basis of their attribute
You can simply use Array.reduce()
to group items by semester. Object.values()
on the map gives you the desired result.
var array=[{ semster:1, name:"Book1" }, { semster:1, name:"Book2" }, { semster:2, name:"Book4" }, { semster:3, name:"Book5" }, { semster:3, name:"Book6" }, { semster:4, name:"Book7" }];
var result = Object.values(array.reduce((a, curr)=>{ (a[curr.semster] = a[curr.semster] || []).push(curr); return a;},{}));
console.log(result);
split an array into two based on condition using javascript
You could take an array and push the objects according their availability with a single loop.
const
data = [{ product_id: 4, product_name: "Samsung", category_name: "Tv and home appliance", is_Available: 1 }, { product_id: 8, product_name: "Apple", category_name: "Home gadgets", is_Available: 1 }, { product_id: 9, product_name: "Verifone", category_name: "Electronics", is_Available: 0 }],
result = data.reduce((r, o) => {
r[o.is_Available ? 'availableData' : 'notAvailableData'].push(o);
return r;
}, { availableData: [], notAvailableData: [] });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related Topics
Javascript String With New Line - But Not Using \N
Check If Image Exists on Server Using JavaScript
Save State When Refresh Page - Reactjs
Trigger Event When Element Becomes Visible With Ngif
Get the Contents of a Table Row With a Button Click
How to Change Text Value Upon Button Press in React Native
Transforming Null into Empty String in JavaScript
Vue.Js - How to Call Method from Another Component
How to Extract Data from Json Nested Objects
How to Get the Value by a Key from a Super Nested Json
React-Native: Application Has Not Been Registered Error
Restrict to 2 Decimal Places in Keypress of a Text Box
How to Update a Variable After Button Click
Multiple Key Names, Same Pair Value
Import Image from Json Source (Create-React-App)
Is It Any Limit for Post Data Size in Ajax