DEV Community

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

Create Linked List with .reduce

alekseikorolev profile image AlekseiKorolev ・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)

Forem Open with the Forem app