Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split array dynamically based on single value in JavaScript Node.js

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

like image 975
DiPix Avatar asked Oct 18 '22 10:10

DiPix


1 Answers

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>');
like image 100
Nina Scholz Avatar answered Oct 21 '22 05:10

Nina Scholz