0

I want to return array with properties which not matched by valuesToCompare array values

const arr = [
{value: "test1", name: "name1"},
{value: "test2", name: "name1"},
{value: "test3", name: "name1"},
{value: "test3", name: "name2"},
{value: "test4", name: "name2"},
]

const valuesToCompare = ["test1", "test2", "test3", "test4"]

expected output

[
{value: "test4", name: "name1"},
{value: "test1", name: "name2"},
{value: "test2", name: "name2"},
]
5
  • 1
    The question isn't clear, explain it better Commented Dec 23, 2020 at 7:27
  • What is the logic behind matching? Commented Dec 23, 2020 at 7:29
  • Need details or clarity. valuesToCompare contains test3 then why is it not a part of the output? Commented Dec 23, 2020 at 7:31
  • i want to return values which was not existed in values in arr Commented Dec 23, 2020 at 7:33
  • Yeah, it's neither excluding nor matching valuesToCompare Commented Dec 23, 2020 at 7:33

2 Answers 2

2

I'm not sure whether you want to match or exclude based on an array of values, so providing both:

const arr = [{
    value: "test1",
    name: "name1"
  },
  {
    value: "test2",
    name: "name1"
  },
  {
    value: "test3",
    name: "name1"
  },
  {
    value: "test3",
    name: "name2"
  },
  {
    value: "test4",
    name: "name2"
  },
]

const valuesToCompare = ["test1", "test2"]

const excluding = arr.filter(obj => !valuesToCompare.includes(obj.value))

console.log("Excluding values:")
console.log(excluding)

const matching = arr.filter(obj => valuesToCompare.includes(obj.value))

console.log("Matching values:")
console.log(matching)

Sign up to request clarification or add additional context in comments.

Comments

1

You could do like below:

  • group the arr by name
  • with each grouped, filter the value
  • flatten each group back into objects

const arr = [
  { value: "test1", name: "name1" },
  { value: "test2", name: "name1" },
  { value: "test3", name: "name1" },
  { value: "test3", name: "name2" },
  { value: "test4", name: "name2" },
];

const valuesToCompare = ["test1", "test2", "test3", "test4"];

const groupByName = arr.reduce((acc, el) => {
  if (acc[el.name]) {
    acc[el.name].push(el.value);
  } else {
    acc[el.name] = [el.value];
  }
  return acc;
}, {});

const res = Object.entries(groupByName)
  .map(([k, v]) => [k, valuesToCompare.filter((vtc) => !v.includes(vtc))])
  .map(([k, v]) => v.map((v) => ({ name: k, value: v })))
  .flat();

console.log(res);
.as-console-wrapper { max-height: 100% !important; }

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.