I need to split array dynamically based on single value in JavaScript.
I've got an array:
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'}
];
And i expect arrays split by Tag, eg.
var Fruit = [
    { Name: 'Apple', Tag: 'Fruit', Price: '2,5'},
    { Name: 'Kiwi', Tag: 'Fruit', Price: '1,5'}
];
var Sport = [
    { Name: 'Bike', Tag: 'Sport', Price: '150'}
];
var Kitchen = [
    { Name: 'Knife', Tag: 'Kitchen', Price: '8'},
    { Name: 'Fork', Tag: 'Kitchen', Price: '7'}
];
If in dataStuff array will be more Tags then in result will be more arrays. Anyway i don't have idea how should I do this. I'm using node.js + Jade (for view), and i think the best idea will be do this at view because i have to put each array in table. Maybe something like this:
// Basic table
tbody
     - each item in dataStuff
         tr
            td= item.Name
            td= item.Tag
            td= item.Price
// Other tables
- each item in dataStuff
    item.Tag.push(item);
    // adding items to array based on Tag
    // probably it won't work 
    // but still how should i draw table?
I would be grateful for any help
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>');
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