2
\$\begingroup\$

I have a function that sorts and groups items inside an array and then adds a corresponding jsx element to the page.

I've already refactored it from 100 lines of code to 44, but I'm sure that its still unreadable pile of spaghetti code. I've tried filtering individuals and groups separately but that just bloats my code to some unbelievable extent so im looking for ways to reduce bloat and improve readability.

// array - array im sorting
// ageStart - minimal age of person
// ageEnd - minimum age of person
// activity & time - specific to the jsx elements inside(dont really     play a role here)
//
function group(array, ageStart, ageEnd, activity, time = '') {
// filtering by political views and age.
    const polViewsLib = array.filter(item => item.polViews === 'Liberal'
        && item.age >= ageStart
        && item.age <= ageEnd)
       //grouping items inside an array using  reduce(groups people     whose age difference is less than 5)
       .reduce((acc, curr, ind, arr) => {
        if (
            !ind
            || curr.age - arr[ind - 1].age > 5
        )acc.push([]);
        acc[acc.length - 1].push(curr);
        return acc;
        }, []);
    const polViewsConservative = array.filter(item => item.polViews === 'Conservative'
        && item.age >= ageStart
        && item.age <= ageEnd).reduce((acc, curr, ind, arr) => {
        if (
            !ind
            || curr.age - arr[ind - 1].age > 5
        )acc.push([]);
        acc[acc.length - 1].push(curr);
        return acc;
    }, []);

 // returning data sorted by age and mapping them to corresponding jsx elements
 return [polViewsLib, polViewsConservative].sort((a,b) => {
 a[0].age - b[0].age;
 }).map((item, index) => {
        const res = item.length > 1 ? (
            <PersonContainer
                key={item[index].id}
                data={item}
                visibility={activity}
                timePeriod={time}
            />
        )
        : (
            <Person
                key={item.id}
                data={item[0]}
                visibility={activity}
                timePeriod={item}
            />
        );
        return res;
    });   
}

Typical item inside array that I process:

  {
     id:151324,
     name: 'John',
     age: 45,
     polViews: 'Liberal', 
  }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.