0
nodesData=[
    {name:'name1'},
    {name:'name2'},
    {name:'name1'},
    {name:'name3'},
]

uniqData=[
    {name:'name1'}
    {name:'name2'}
    {name:'name3'}
]

for (let i = 0; i < nodesData.length; i += 2) {
  const currentSource = nodesData[i];
  const currentTarget = nodesData[i + 1];

  const currentData = {
    source: uniqData.indexOf(currentSource),
    target: uniqData.indexOf(currentTarget),
  };
}

So I've got two lists with objects. First list is list with objects that contains names, and other list is list generated with function that I've made for removing duplicates.The problem is when I use for loop and loop through nodesData list only the first time I get only for source index of -1...why? and other indexOf work expected.

So the console.log would be:

source:-1, target:1

source:0, target:2
3
  • First, you are missing , in uniqData. Second, your code log source: -1, target: -1 twice Commented Feb 3, 2021 at 10:06
  • You should get all -1 for currentData in all iteration. You want to generate uniqData. So, uniqData is empty. and indexOf uniqData will always give you -1 Commented Feb 3, 2021 at 10:16
  • You're comparing objects with a different reference. So the indexOf will always return -1 because for us the values seem similar but actually they aren't Commented Feb 3, 2021 at 10:18

1 Answer 1

1

The objects in the array have differents references even if they looks like they are the same. Basically :

console.log({name: 'name1'} === {name: 'name1'}); // false

It prints false because the compared objects haven't the same references even if they are similar.

So in your example the indexOf method returns -1 because the objects have not the same reference (again even if they looks like they are equal).

Since you can't directly use indexOf you have to first get the object's reference with find and then you can use indexOf, like this :

const nodesData=[
    {name:'name1'},
    {name:'name2'},
    {name:'name1'},
    {name:'name3'},
]

const uniqData=[
    {name:'name1'},
    {name:'name2'},
    {name:'name3'},
]

for (let i = 0; i < nodesData.length; i += 2) {
  const currentSource = nodesData[i];
  const currentTarget = nodesData[i + 1];

  const currentData = {
    source: uniqData.indexOf(uniqData.find(({name}) => name === currentSource.name)),
    target: uniqData.indexOf(uniqData.find(({name}) => name === currentTarget.name)),
  };
  
  console.log(currentData);
}

Note :

I used destructuring in order to directly get the name property

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.