1

So I have an Object that contains multiple Objects

const edges = {
         edge1: {source: "Horse", target: "4_2_0_0_0f"},
         edge2: {source: "Horse", target: "4_2_0_0_0x"},
         edge3: {source: "Horse", target: "4_2_0_2_1h"},
         edge4: {source: "Horse", target: "4_2_4_0_4z"},
         edge5: {source: "Horse", target: "4_2_1_0_0p"},
....}

Now I want to check whether edge2: {source: "Horse", target: "4_2_0_0_0x"} exists in edges or not. What is the fastest way to do that?

3
  • What have you tried and why wasn't it fast enough for you? Commented Aug 9, 2022 at 19:30
  • 1
    Use the Array.some() method with a callback function that checks for the properties you want. Commented Aug 9, 2022 at 19:36
  • 1
    Do you only care about the edge2 property? Then it's even easier. if (edges.edge2.source == 'Horse' && edges.edge2.target == '4_2_0_0_0x') Commented Aug 9, 2022 at 19:38

1 Answer 1

1

You can Array.some to check if at least one of array elements matches your condition. Before that you will need to convert object you array with Object.values:

const edges = {
  edge1: {
    source: "Horse",
    target: "4_2_0_0_0f"
  },
  edge2: {
    source: "Horse",
    target: "4_2_0_0_0x"
  },
  edge3: {
    source: "Horse",
    target: "4_2_0_2_1h"
  },
  edge4: {
    source: "Horse",
    target: "4_2_4_0_4z"
  },
  edge5: {
    source: "Horse",
    target: "4_2_1_0_0p"
  },
}

function existsEdge(source, target) {
  return Object.values(edges).some(v => v.source === source && v.target === target)
}

console.log(existsEdge('Horse', '4_2_0_0_0x'))

This is effective if you wish to check only once. If you wish to check multiple times, consider using different data structure with fasters checks. Example using Set:

const edges = {
  edge1: {
    source: "Horse",
    target: "4_2_0_0_0f"
  },
  edge2: {
    source: "Horse",
    target: "4_2_0_0_0x"
  },
  edge3: {
    source: "Horse",
    target: "4_2_0_2_1h"
  },
  edge4: {
    source: "Horse",
    target: "4_2_4_0_4z"
  },
  edge5: {
    source: "Horse",
    target: "4_2_1_0_0p"
  },
}

const index = new Set(Object.values(edges).map(v => `${v.source}:${v.target}`))

function existsEdge(source, target) {
  return index.has(`${source}:${target}`)
}

let result = undefined
for (let i = 0; i < 10000000; i++) {
  result = existsEdge('Horse', '4_2_1_0_0p')
}

console.log(result)

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.