Home > Enterprise >  how to get the first item in nested, filtered array in javascirpt
how to get the first item in nested, filtered array in javascirpt

Time:01-29

I've got an array:

const aContracts = [[ '0x8ae127d224094cb1b27e1b28a472e588cbcc7620', 0 ],
  [ '0xcbf4ab00b6aa19b4d5d29c7c3508b393a1c01fe3', 0 ],
  [ '0x03cd191f589d12b0582a99808cf19851e468e6b5', 0 ],
  [ '0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a', 1 ]]

And I'm trying to filter using the second item in each sub-array. So I used:

const aGoodContracts = aContracts.filter(contracts => contracts[1]===1);

And I get:

[["0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a", 1]]

However, I want [EDIT I want an array of all the "good" contracts]:

"0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a"

So I tried a solution I found here: const aGoodContracts = aContracts.map(k => k.filter(contracts => contracts[1]===1));

But I get:

[[], [], [], []]

What am I missing?

CodePudding user response:

Just map() your result to pick out the first element in the array. This will leave you with an array, and if you just want the first value (like your expected output) grab the zero index element.

const aContracts = [[ '0x8ae127d224094cb1b27e1b28a472e588cbcc7620', 0 ],
  [ '0xcbf4ab00b6aa19b4d5d29c7c3508b393a1c01fe3', 0 ],
  [ '0x03cd191f589d12b0582a99808cf19851e468e6b5', 0 ],
  [ '0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a', 1 ]]

const aGoodContracts = aContracts.filter(contracts => contracts[1]===1).map(c => c[0]);
console.log(aGoodContracts);
console.log(aGoodContracts[0]);

CodePudding user response:

You can try this

const aContracts = [[ '0x8ae127d224094cb1b27e1b28a472e588cbcc7620', 0 ],
  [ '0xcbf4ab00b6aa19b4d5d29c7c3508b393a1c01fe3', 0 ],
  [ '0x03cd191f589d12b0582a99808cf19851e468e6b5', 0 ],
  [ '0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a', 1 ]]
const aGoodContracts = aContracts.filter(contracts => contracts[1]===1)[0]
console.log(aGoodContracts[0])
  •  Tags:  
  • Related