1

I have this scenario where I need to fetch unique values of all objects based on a dynamically passed property . I have tried the following approach but does not seem like working.

var arr = [
  {
    id: "1",
    type: "x",
    source: {
      val1: "3",
      val2: "4",
      val3: "6",
    },
  },
  {
    id: "1",
    type: "x",
    source: {
      val1: "3",
      val2: "4",
      val3: "6",
    },
  },
  {
    id: "1",
    type: "x",
    source: {
      val1: "4",
      val2: "5",
      val3: "6",
    }
  }
];

Now say I pass val1 it should give me unique values 3,4 and if I pass val2 it should give me 4,5. P.S : I will only pass the parameter that are present inside source property.

Approach that I have tried:

 calculate = (param) =>
 {
   let uniqueValues = Array.from(
        new Set(arr.map((arr: any) => arr[param]))
   );
 }
1
  • The structure of your data will always be the same or it can be different. Commented Jul 4, 2019 at 12:21

2 Answers 2

2

It looks like, you need the source property as well.

new Set(arr.map((o: any) => o.source[param]))
Sign up to request clarification or add additional context in comments.

Comments

0

You can use map to get source values and then reduce inuque values:

const arr = [
  {
    id: "1",
    type: "x",
    source: {
      val1: "3",
      val2: "4",
      val3: "6",
    },
  },
  {
    id: "1",
    type: "x",
    source: {
      val1: "3",
      val2: "4",
      val3: "6",
    },
  },
  {
    id: "1",
    type: "x",
    source: {
      val1: "4",
      val2: "5",
      val3: "6",
    }
  }
];

function calculate(data, param) {
  return data.map(x => {
    return (x.source || {})[param];
  }).reduce((acc, val) => {
    if (acc.indexOf(val) === -1)
      acc.push(val);
    return acc;
  }, []);
}

console.log(calculate(arr, "val1"));
console.log(calculate(arr, "val2"));

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.