DEV Community

Cover image for Create Linked List with .reduce
AlekseiKorolev
AlekseiKorolev

Posted on

Create Linked List with .reduce

Easy, readable, and simple way create linked list use built-in function.

    // Array
    const linkedList = arr => arr
        .reduce((next, val) => { return {val, next} }, null)

Can use any type of data

    // Map or Set
    const linkedList = map => Array.from(map.values())
        .reduce((next, val) => { return {val, next} }, null)

Can use .sort or .reverse() to change direction and order

    // Object
    const linkedList = obj => Object.keys(obj)
        .map(key => obj[key])
        .sort((a, b) => b - a)
        .reduce((next, val) => { return {val, next} }, null)

Top comments (0)