Sort a list by property and add an object before changing every first letter in JavaScript

So, I am trying to make the UI as follows:

enter image description here

And I have an array of users

[{name: 'Julia'}, {name: 'Ismeh'}, {name: 'Alison'}, {name: 'Andrea'}, {name: 'Betty'}]

What I'm trying to do is sort the array by the first letter of the name property and add a header object in front of each. For example, in the picture you can see the letters A, B, I and J as headings.

Now I started working as follows:

    let final = []
    // sort by first letter
    const sortedUsers = state.test_list.sort((a, b) => a.name.localeCompare(b.name))
    for (let x = 0; x < sortedUsers.length; x++) {
        const user = sortedUsers[x].name
        if (user.charAt(0) === 'A') {
            const checkIfExists = final.findIndex((f) => f.header === 'A')
            // add the header A if it doesn't exist
            if (checkIfExists < 0) final.push({header: 'A'})
        }
        else if (user.charAt(0) === 'B') {
            const checkIfExists = final.findIndex((f) => f.header === 'B')
            // add the header B if it doesn't exist
            if (checkIfExists < 0) final.push({header: 'B'})
        }
        // else if up to the letter Z
        final.push(user)
    }

and if I write the final array, I get:

enter image description here

what is right.

My concern is that the code is very long, and I have no idea whether it is possible to optimize or reduce the code.

Is there any other way to do something like this? Any help would be greatly appreciated.

+4
source share
5 answers

, , .reduce:

const unsortedPeople = [{name: 'Julia'}, {name: 'Ismeh'}, {name: 'Alison'}, {name: 'Andrea'}, {name: 'Betty'}];
const sortedUsers = unsortedPeople.sort((a, b) => a.name.localeCompare(b.name))
const final = sortedUsers.reduce((finalSoFar, user) => {
  const thisUserFirstChar = user.name[0];
  if (finalSoFar.length === 0) addHeader();
  else {
    const lastUserFirstChar = finalSoFar[finalSoFar.length - 1].name[0];
    if (lastUserFirstChar !== thisUserFirstChar) addHeader();
  }
  finalSoFar.push(user);
  return finalSoFar;
  function addHeader() {
    finalSoFar.push({ header: thisUserFirstChar });
  }
}, []);

console.log(final);
Hide result
+1

, ? . Array#reduce .

Object#keys, :

let data = [{
  name: 'Julia'
}, {
  name: 'Ismeh'
}, {
  name: 'Alison'
}, {
  name: 'Andrea'
}, {
  name: 'Betty'
}];

let combined = data.reduce((result, item) => {
  let letter = item.name[0].toUpperCase();
  if (!result[letter]) {
    result[letter] = [];
  }

  result[letter].push(item);
  return result;
}, {});

console.log(combined);

// Iterate over the result
Object.keys(combined).forEach(key => {
  // key will be the first letter of the user names and
  // combined[key] will be an array of user objects
  console.log(key, combined[key]);
});
Hide result

- , Array#sort.

+3

, . , :

var users = [{name: 'Julia'}, {name: 'Ismeh'}, {name: 'Alison'}, {name: 'Andrea'}, {name: 'Betty'}]

const sortedUsers = users.sort((a, b) => a.name.localeCompare(b.name))
var currentHeader 
let final = sortedUsers.reduce((a, user) => {
    if (currentHeader !==  user.name[0]) {
        currentHeader = user.name[0]
        a.push({header: currentHeader})
    }
    a.push(user)
    return a
},[])

console.log(final)
Hide result
+1

:

const users = [{name: 'Julia'}, {name: 'Ismeh'}, {name: 'Alison'}, {name: 'Andrea'}, {name: 'Betty'}];

let lastIndex;
let result = [];
users.sort((a, b) => {
  return a.name > b.name;
}).forEach((user) => {
  const index = user.name.charAt(0);
  if (index !== lastIndex) {
    result.push({
      header: index
    });
  }
  lastIndex = index;
  result.push(user.name);
}, []);






console.log(result);
Hide result
+1

_.orderBy(collection, [iteratees=[_.identity]], [orders]) _.groupBy(collection, [iteratee=_.identity]) lodash.

  • orderBy _.sortBy, , . , . "desc" "asc" .
  • groupBy , , iteratee. . , . : ().

// The `_.property` iteratee shorthand.
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }

// Sort by `user` in ascending order and by `age` in descending order.
_.orderBy(users, ['user', 'age'], ['asc', 'desc']);

lodash

let myArr = [{
  name: 'Julia'
}, {
  name: 'Ismeh'
}, {
  name: 'Andrea'
}, {
  name: 'Alison'
}, {
  name: 'Betty'
}];

myArr = _.orderBy(myArr, ['name'], ['asc']);

let r = _.groupBy(myArr, o => {
  return o.name.charAt(0).toUpperCase();
})

console.log(r);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Hide result

ES5

var arr = [{
    name: 'Julia'
  }, {
    name: 'Ismeh'
  }, {
    name: 'Andrea'
  }, {
    name: 'Alison'
  }, {
    name: 'Betty'
  }],
  fChar = '';
  
  
arr = arr.sort(function(a, b) {
  a = a.name.toUpperCase(); // ignore upper and lowercase
  b = b.name.toUpperCase(); // ignore upper and lowercase
  return a < b ? -1 : (a > b ? 1 : 0);
}).reduce(function(r, o) {
  fChar = o.name.charAt(0).toUpperCase();
  if (!r[fChar]) {
    r[fChar] = [];
  }
  r[fChar].push({
    name: o.name
  });
  return r;
}, {});

console.log(arr);
Hide result

ES6

const arr = [{
    name: 'Julia'
}, {
    name: 'Ismeh'
}, {
    name: 'Andrea'
}, {
    name: 'Alison'
}, {
    name: 'Betty'
}];

let result = arr.sort((a, b) => {
    a = a.name.toUpperCase(); // ignore upper and lowercase
    b = b.name.toUpperCase(); // ignore upper and lowercase
    return a < b ? -1 : (a > b ? 1 : 0);
}).reduce((r, o) => {
    let fChar = o.name.charAt(0).toUpperCase();
    if (!r[fChar]) {
        r[fChar] = [];
    }
    r[fChar].push({
        name: o.name
    });
    return r;
}, {});

console.log(result);
Hide result
+1

Source: https://habr.com/ru/post/1695380/


All Articles