1

Array filtering not working as expected:

function getTest( myArray ) { 
  keySetTest = new Set('B-L002');

  var t2= myArray[2][0];
  var myResult = myArray.filter(dataRow =>keySetTest.has(dataRow[0]));   

  return myResult;
};

In the debugger it looks like this:

Debug

Why is myResult empty? As can be seen from variable t2 it should contain at least the entry myArray[2],right? I am using this logic almost identical in another context and it works fine.

3
  • There is a problem with your posting of code format code Commented Jan 30, 2023 at 19:49
  • Where is myArray being declared? Commented Jan 30, 2023 at 23:04
  • @Cooper thank you for pointing out the problem with the format of the code, but I cant figure out what you see as problematic? I marked the code in the editor and hit the { }-button so it should be ok, or? Commented Feb 2, 2023 at 10:42

1 Answer 1

2

About your question of Why is myResult empty?, when I saw your script, it seems that keySetTest = new Set('B-L002'); is required to be modified. Because I think that in your situation, when keySetTest = new Set('B-L002'); is used, each character is split like [ 'B', '-', 'L', '0', '2' ]. I thought that this might be the reason for your current issue.

When your script is modified, how about the following modification?

From:

keySetTest = new Set('B-L002');

To:

var keySetTest = new Set(['B-L002']);

Testing:

When the modified script is tested using a sample value, it becomes as follows.

var myArray = [["B-L002", "b1", "c1"], ["a2", "b2", "c2"], ["B-L002", "b3", "c3"]];
var keySetTest = new Set(['B-L002']);
var myResult = myArray.filter(dataRow => keySetTest.has(dataRow[0]));
console.log(myResult)

Note:

  • In this sample, I guessed your sample value of myArray. When you use this modified script in your actual situation, when your unexpected result is obtained, please provide the sample value of myArray and your sample expected value. By this, I would like to confirm it.

  • In your situation, the following modified script might be able to also obtain the same result.

      var myArray = [["B-L002", "b1", "c1"], ["a2", "b2", "c2"], ["B-L002", "b3", "c3"]];
      var myResult = myArray.filter(dataRow => dataRow[0] == "B-L002");
      console.log(myResult)
    

Reference:

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

1 Comment

Your suggestion solved my problem. Thank you so much!

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.