1

Given the example structure,

const selectedEdges = [
    { id: 'e1', start: 'n2', end: 'n1' },
    { id: 'e3', start: 'n6', end: 'n2' },
]

How do I compare nested array (nestedNodeNodeIds) with a plain array and the object

const nestedNodeIds = [['n1', 'n2'], ['n6']]
selectedEdges
  .filter(({ start, end }) => !nestedNodeIds.includes(start) || !nestedNodeIds.includes(end)))
  .filter(Boolean);

and return [{ id: 'e3', start: 'n6', end: 'n2' }]...??

It's returning [{ id: 'e1', start: 'n2', end: 'n1' }, { id: 'e3', start: 'n6', end: 'n2' }]

5
  • 1
    includes() comapres object references. Since nestedNodeIds is initialized with two array literals, they're not gonna match anything in edgeById. Also a string doesn't have the properties start and end, so I'm guessing your definition of selectedEdges is incorrect. Commented Apr 24, 2020 at 2:58
  • Good catch! Thanks! I edited it Commented Apr 24, 2020 at 3:01
  • This is a pretty complex problem. Must be a big challenge @PatrickRoberts Commented Apr 24, 2020 at 3:03
  • Does this answer your question? JavaScript - Filter Nested Arrays Commented Apr 24, 2020 at 3:35
  • No different case ;; Commented Apr 24, 2020 at 3:35

2 Answers 2

1

This should work:

const selectedEdges = [
  { id: "e1", start: "n2", end: "n1" },
  { id: "e3", start: "n6", end: "n2" },
];
const nestedNodeIds = [["n1", "n2"], ["n6"]];

selectedEdges
  .filter(
    ({ start, end }) =>
      nestedNodeIds.filter((x) => x.includes(start) && x.includes(end))
        .length === 0
  )
  .filter(Boolean);

You have to iterate over each nestedNodeIds sub-array and search in it.

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

3 Comments

I think it will not be optimal, as it's having O(n**2) complexity.
Yes, it's not optimal. But it returns right value: [{"id":"e3","start":"n6","end":"n2"}]
@hellofanengineer please, upvote and accept if you found this answer helpful. Thanks!
-1

Just do a quick array map before comparison like that:

const selectedEdges = [
    { id: 'e1', start: 'n2', end: 'n1' },
    { id: 'e3', start: 'n6', end: 'n2' },
]
const nestedNodeIds = [];
const _temp = [['n1', 'n2'], ['n6']];

_temo.map(v => {nestedNodeIds.push(...v)})  // Appending all the values in a plain array

selectedEdges
  .filter(({ start, end }) => !nestedNodeIds.includes(start) || !nestedNodeIds.includes(end)))
  .filter(Boolean);

3 Comments

This is returning [{ id: 'e1', start: 'n2', end: 'n1' }, { id: 'e3', start: 'n6', end: 'n2' }] :(
How do you wanna the answer, explain a little
That's not what he wants. You could just do nestedNodeIds.flat() by the way

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.