0

I want to Compare 2 arrays arr1 and arr2. If an array of arr1 is not present in arr2 then I want the first element of that array.

const arr1 = [
  ["item 1", "item 1.1", "item 1.2"],
  ["item 2", "item 2.1", "item 2.2"],
  ["item 3", "item 3.1", "item 3.2"],
  ["item 4", "item 4.1", "item 4.2"],
];


const arr2 = [
  ["item 1", "item 1.1", "item 1.2"],
  ["item 2", "item 2.1", "item 2.2"],

];

const newArr = () => {
  return arr1.filter(arr => arr2.some(arr2 => arr2[0] != arr[0]))

};

console.log(newArr())

// Expected output [ 'item 3', 'item 4' ]

2
  • It is not so clear. what exactly do you want and what is your expected output? Commented Jun 3, 2021 at 8:18
  • the expected output is given below in the comments @decpk Commented Jun 3, 2021 at 8:21

2 Answers 2

2

You can easily achieve this result using reduce and find.

const arr1 = [
  ["item 1", "item 1.1", "item 1.2"],
  ["item 2", "item 2.1", "item 2.2"],
  ["item 3", "item 3.1", "item 3.2"],
  ["item 4", "item 4.1", "item 4.2"],
];

const arr2 = [
  ["item 1", "item 1.1", "item 1.2"],
  ["item 2", "item 2.1", "item 2.2"],
];

const result = arr1.reduce((acc, curr) => {
  const [first] = curr;
  const isExist = arr2.find((nestedArray) => nestedArray[0] === first);
  if (!isExist) acc.push(first);
  return acc;
}, []);

console.log(result);

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

1 Comment

@mplungjan forgot to console.log. Thanks for pointing out.
1

If you're working with large arrays, I would recommend you stringify them for comparison like the example code below.

const arr1 = [
  ["item 1", "item 1.1", "item 1.2"],
  ["item 2", "item 2.1", "item 2.2"],
  ["item 3", "item 3.1", "item 3.2"],
  ["item 4", "item 4.1", "item 4.2"]
];

const arr2 = [
  ["item 1", "item 1.1", "item 1.2"],
  ["item 2", "item 2.1", "item 2.2"]
];

const notMatchingItems = [];

for (var i = 0; i < arr1.length; i++) {
  if (JSON.stringify(arr1[i]) !== JSON.stringify(arr2[i])) {
    notMatchingItems.push(arr1[i][0]);
  }
}

console.log(notMatchingItems);

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.