Skip to content

Instantly share code, notes, and snippets.

@kevdougful
Created February 16, 2018 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevdougful/54adb27ee5b764db64aefe1f57bbcd46 to your computer and use it in GitHub Desktop.
Save kevdougful/54adb27ee5b764db64aefe1f57bbcd46 to your computer and use it in GitHub Desktop.
NodeJS Dataframe
// Go from this:
const data = [
{
id: 1,
response: 'weight',
value: 34.2
},
{
id: 1,
response: 'height',
value: 110.0
},
{
id: 2,
response: 'weight',
value: 22.1
},
{
id: 3,
response: 'weight',
value: 52.1
},
{
id: 3,
response: 'height',
value: 75.2
}
]
// To this:
const dataframe = {
id: [1, 2, 3],
weight: [34.2, 22.1, 52.1],
height: [110.0, null, 75.2]
}
// With a function that looks like this:
const func = (longData, columnKey, valueKey) => {
}
// And would be called like this
func(data, 'response', 'value')
@kevdougful
Copy link
Author

Look at this ugliness:

// Go from this:
const data = [
    {
        id: 1,
        response: 'weight',
        value: 34.2
    },
    {
        id: 1,
        response: 'height',
        value: 110.0
    },
    {
        id: 2,
        response: 'weight',
        value: 22.1
    },
    {
        id: 3,
        response: 'weight',
        value: 52.1
    },
    {
        id: 3,
        response: 'height',
        value: 75.2
    }
]
// To this:
const dataframe = {
    id: [1, 2, 3],
    weight: [34.2, 22.1, 52.1],
    height: [110.0, null, 75.2]
}

// With a function that looks like this:
const pivot = (longData, idKey, columnKey, valueKey) => {
    return longData.reduce((df, dp) => {
        let row = findRow(df[idKey], dp[idKey])
        df[idKey] = row[0]
        df[dp[columnKey]][row[1]] = dp[valueKey]
        //df[dp[columnKey]][row[1]] = dp[valueKey]
        // df[idKey] = df[df[idKey].indexOf(dp[idKey]) < 0 ? 0 : df[idKey].indexOf[dp[idKey]]]
        console.log(df)
        return df
    }, {
        id: [],
        height: [],
        weight: []
    })
}

const findRow = (idArr, id) => {
    if (idArr.length === 0) {
        idArr.push(id)
        return [idArr, 0]
    } else if (idArr.indexOf(id) < 0) {
        idArr.push(id)
        return [idArr, idArr.length]
    } else {
        return [idArr, idArr.indexOf(id)]
    }
}

// And would be called like this
const result = pivot(data, 'id', 'response', 'value')
console.log(result)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment