0

Im passing an array of arrays to a function. I want to:

  1. filter each array for unique values
  2. concatenate the filtered arrays into a single array
  3. coerce the array into a Set, therefore creating a single iterable object of unique values.

I can't seem to scope the variables within/out of function so that it allows me to use the function with any size array of arrays. I don't have any affection for anything but the outcome - a single iterable object of the uniques values amongst the array of arrays.

Pseudo code:

function getDataForHistogram(shipments, groupKeys) {
    console.log('@getDataForHistogram');
    let uniqueArry = [];
    groupKeys.forEach(groupKey => {
        uniqueArry.concat(shipments.reduce((accumulator, element) => {. //pseudo, I know concat returns an array
            if ((accumulator.indexOf(Math.ceil(element[groupKey])) < 0)) {
                accumulator.push(Math.ceil(element[groupKey]));
            }
            return accumulator;
        },[])
    })
    let uniqueSet = new Set(...uniqueArry);
    let range = {
        min: Math.min(uniqueSet),
        max: Math.max(uniqueSet)
    };
    console.log(uniqueSet);
    console.log(range.min, range.max);
}

I'm flummoxed... The only alternative way that I have thought of is to count the number of arrays and iterate over each three recursively.

1
  • 1
    Can you give us an example of the array you are using and show the expected result after the filter? Commented Sep 1, 2020 at 0:10

1 Answer 1

2

There's no need for uniqueArray. Just add the elements to the Set, it will discard duplicates automatically.

function getDataForHistogram(shipments, groupKeys) {
  console.log('@getDataForHistogram');
  let uniqueSet = new Set;
  groupKeys.forEach(groupKey =>
    shipments.forEach(element => uniqueSet.add(Math.ceil(element[groupKey])))
  );
  let range = {
    min: Math.min(uniqueSet),
    max: Math.max(uniqueSet)
  };
  console.log(uniqueSet);
  console.log(range.min, range.max);
}
Sign up to request clarification or add additional context in comments.

Comments

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.