Skip to content

Instantly share code, notes, and snippets.

@leobalter
Forked from anonymous/groupMessagesByUser.js
Created April 11, 2017 20:38
Show Gist options
  • Select an option

  • Save leobalter/df3dd9032c04ff4a84a1cc52748cb4e6 to your computer and use it in GitHub Desktop.

Select an option

Save leobalter/df3dd9032c04ff4a84a1cc52748cb4e6 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Apr 11, 2017.
    25 changes: 25 additions & 0 deletions groupMessagesByUser.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    onst getLast = (arr, def) => (arr[arr.length - 1] || def)

    const getLastUser = arr => {
    const last = getLast(arr, [])
    return getLast(last, {})
    }

    const pushIntoLast = (arr, value) => {
    const last = getLast(arr, [])
    last.push(value)
    return arr
    }

    const groupMessagesByUser = messages => {
    console.log(messages)
    return messages.reduce((acc, current) => {
    const prevUser = getLastUser(acc)

    if (prevUser.users_id === current.users_id) {
    return pushIntoLast(acc, current)
    }

    return [ ...acc, [ current ] ]
    }, [])
    }