Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Crossfilter how do I return an array of all the id values for a specific type

Forgive me, I'm not sure I'm approaching this problem correctly.

I have some data (many thousands of elements) with a type and an ID:

const data = [
  { type: 'foo', id: 1 },
  { type: 'foo', id: 3 },
  { type: 'foo', id: 5 },
  { type: 'baz', id: 8 },
  { type: 'baz', id: 10 },
  { type: 'bar', id: 11 },
  { type: 'bar', id: 13 },
  { type: 'bar', id: 17 },
  ...
];

With crossfilter, I want to filter by a type and return an array of all their ids.

For example: all the type 'bar' should return [10, 11, 13, 17]

My attempt was to group reduce. But I didn't get very far with it:

let ndx = crossfilter(data);
let d = ndx.dimension(d => d.type);
let reduceAdd = (p, v) => p.push(v);
let reduceRemove = (p, v) => p.filter(i => i !== v);
let reduceInitial = () => ([]);

And then something like:

d.group().reduce(reduceAdd, reduceRemove, reduceInitial)
like image 694
Rimian Avatar asked Dec 04 '18 10:12

Rimian


2 Answers

You should use filter method in combination with map and destructing assignment.

const data = [ { type: 'foo', id: 1 }, { type: 'foo', id: 3 }, { type: 'foo', id: 5 }, { type: 'baz', id: 8 }, { type: 'baz', id: 10 }, { type: 'bar', id: 11 }, { type: 'bar', id: 13 }, { type: 'bar', id: 17 }, ], type = 'bar';
console.log(data.filter(elem => elem.type == type).map(({id}) => id));
like image 159
Mihai Alexandru-Ionut Avatar answered Sep 27 '22 22:09

Mihai Alexandru-Ionut


What you've got looks pretty much correct with me. You just have to query your group by saving it to a variable

var grp = d.group().reduce(reduceAdd, reduceRemove, reduceInitial)

and then query it like

grp.top(Infinity)

This will return an array of objects. The key of one of the objects will be bar and the value of that object will be the array of records where type is bar.

like image 32
Ethan Jewett Avatar answered Sep 27 '22 23:09

Ethan Jewett