2

I have an array with objects that looks like this:

0:
depth:0
id:37
index:0
label:"user"
name:"r"
next:(3) [265, 355, 387]

I want to match an id with the values inside next: Array(3)

findNext = function(idToMatch) {
    const nodes = this.state.nodes;
    for (let i = 0; i < nodes.length; i++){
        if (nodes.next[i] === idToMatch) { return nodes[i].id }
    }
};

idToMatch is one integer, just like id:37 in above example.

const nodes = this.state.nodes; is the array that contains objects as the one above.

How can I check if this.state.nodes[i].next contains the idToMatch and, if so, return this.state.nodes[i].id?

1
  • 2
    Can you give a fuller description of the nodes? JSON format, perhaps? Commented May 14, 2018 at 8:49

3 Answers 3

1

If you're ok with using ES2016's Array.prototype.includes();

findNext = function(idToMatch) {
    const nodes = this.state.nodes;
    let matches = [];

    for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].next.includes(idToMatch)) matches.push(nodes[i].id);
    }

    return matches;
};

If not:

findNext = function(idToMatch) {
    const nodes = this.state.nodes;
    let matches = [];

    for (let i = 0; i < nodes.length; i++){
        if (nodes[i].next.indexOf(idToMatch) > -1) matches.push(nodes[i].id);
    }

    return matches;
};
Sign up to request clarification or add additional context in comments.

2 Comments

This works thanks! but if a node is connected to multiple other nodes, it doesn't return all the values. Would this be a good way to adjust the code? if (nodes[i].next.includes(idToMatch)) { arr.push(nodes[i].id) } and declare let arr = []; on top?
Right, if there is the possibility for multiple nodes to match that is the correct way. I'll edit my answer to reflect that.
0

You can use .find to get the matched object and then get any property of the object you want

this.state.nodes[i].next.find(o=> o === idToMatch)

Comments

0

just add another for loop inside the loop? like this:

const findNext = function(idToMatch) {
    const nodes = this.state.nodes;
    for (let i = 0; i < nodes.length; i++){
        for(let node in nodes.next){
           if(node.id == idToMatch){
             return node;
           } 
        }
        if (nodes.next[i] === idToMatch) { return nodes[i].id }
    }
};

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.