• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How to chain map and filter functions with good readability?

Resolved: How to chain map and filter functions with good readability?

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I’m going to use the code below. But I’m not sure it’s readable.
I wonder if there is a code style commonly used in method chaining that improves the readability of this code. (like indentation, line breaks, etc.)

Question


How to increase this code’s readability? Any recommendation?
const words = Object.entries(data).map((item) => item[1].words.filter((v) => v.wordId)));
Input data
//data looks like this
[
  {
    id: '...',
    words: { id:1, wordId: '0nN1R9AlPGrH67', word: {text:'aa', originalText:'aa'} },
  },
]
Expected output
I want to extract only the value where wordId exists.

Try


const words = Object.entries(data)
        .map((item) => item[1].words
            .filter((v) => v.wordId)),
        );

Answer:

As a suggestion, instead of writing a one line chain, you could break it down into multiple variables and combine them. This should increase code modularity and make it more readable. See an example below:
const objData = Object.entries(data);
const callbackFilter = (item) => item[1].words.filter((v) => v.wordId);
const dataArray = objData.map(callbackFilter);

If you have better answer, please add a comment about this, thank you!

javascript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: significance letter above bar graphic in wrong order

01/04/2023

Resolved: VBA – Applying border around the areas with value/text

01/04/2023

Resolved: How can I implement a function depending on picked up items?

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.