DEV Community

loading...
Cover image for Create Linked List with .reduce

Create Linked List with .reduce

AlekseiKorolev
Try to code
・1 min read

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)

Discussion (0)