2

I'm trying to find similar items amongs a dynamic amount of arrays, For example I might have 2 or 3 arrays with data in them, and want to find the which items exist between all of them.

At the minute i've got this "working" but really ugly code which won't scale past 3 items. The GDAX, PLNX etc are all bools which I have available to tell me whether this option is selected.

The intersectionBy is a lodash helper function with further information available here https://lodash.com/docs/4.17.4#intersectionBy

  let similarItems = [];
  similarItems = GDAX && PLNX && BTRX ? _.intersectionBy(data.BTRX, data.PLNX, data.GDAX, 'pair') : similarItems;
  similarItems = GDAX && PLNX && !BTRX ? _.intersectionBy(data.PLNX, data.GDAX, 'pair') : similarItems;
  similarItems = GDAX && !PLNX && BTRX ? _.intersectionBy(data.BTRX, data.GDAX, 'pair') : similarItems;
  similarItems = !GDAX && PLNX && BTRX ? _.intersectionBy(data.BTRX, data.PLNX, 'pair') : similarItems;
0

2 Answers 2

2

This should do the job

const input = ['GDAX', 'PLNX', 'BTRX']; // here you pass the strings that are given

const result = _.intersectionBy.apply(_, input.map(name => data[name]).concat(['pair']));

The input could also somehow automized, e.g. giving the object of true / false values for each name, so

const inputObject = { GDAX: true, PLNX: false, BTRX: true };

const names = ['GDAX', 'PLNX', 'BTRX'].filter(name => inputObject[name]);

const result = _.intersectionBy.apply(_, names.map(name => data[name]).concat(['pair']));
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! That's exactly the kind of thing I was after, much appreciated i'll try hooking it up now
2

For readability and easy maintainability, I'd go with explicitly building a selection according to your boolean flags:

let selection = [];
if (GDAX) selection.push(data.GDAX);
if (PLNX) selection.push(data.PLNX);
if (BTRX) selection.push(data.BTRX);
const result = _.intersectionBy(...selection, 'pair'); 

1 Comment

Another cool answer thanks, forgot you can just spread arrays as arguements now as a neater way to .apply, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.