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:
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.
CodePudding user response:
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 ofmyArray
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)