1

I have an array where each element in the array (representing a Supreme Court Chief Justice) contains an array of data points (the Chief Justice's name, number of disputes and year).

For each element in the top-level array, I need to sort the lower-level array in ascending order by year.

I attempted to sort year by ascending order using the following:

  nested_data.forEach(function(d) {
    d.values.sort(d3.ascending(d.values.year));
  });

But it did not sort the lower-level array in ascending order by year.

Here is the console.log of my nested data to show its structure.

Array[5]
  0:Object
    key:"Vinson"
    values:Array[7]
      0:Object
        chief:"Vinson"
        disputes:142
        year:Tue Jan 01 1946 00:00:00 GMT+0800 (CST)
      1:Object
      2:Object
      3:Object
      4:Object
      5:Object
      6:Object
  1:Object
    key:"Warren"
    values:Array[16]
  2:Object
    key:"Burger"
    values:Array[17]
  3:Object
    key:"Rehnquist"
    values:Array[19]
  4:Object
    key:"Roberts"
    values:Array[11]

How can I sort the lower-level array in ascending order by year?

0

1 Answer 1

2

This is the function:

nested_data.forEach(function(d) {
    d.values.sort(function(a, b) {
        return d3.ascending(+a.year, +b.year)
    });
});

Your original function had two problems:

  1. Since you're sorting the values arrays, you don't need to repeat values in the compareFunction
  2. When specified, compareFunction uses two parameters, normally named a and b. You have to put d3.ascending inside compareFunction. Have a look here.

Here is a demo with a bogus data:

var data = [{
        key: "foo",
        values: [{
            chief: "Bob",
            year: 1982
        }, {
            chief: "Tom",
            year: 1977
        }, {
            chief: "Carla",
            year: 2010
        }, {
            chief: "Ana",
            year: 1999
        }]
    }, {
        key: "bar",
        values: [{
            chief: "Bill",
            year: 2009
        }, {
            chief: "Ted",
            year: 2014
        }]
    }, {
        key: "baz",
        values: [{
            chief: "Fred",
            year: 1998
        }, {
            chief: "Su",
            year: 1992
        }, {
            chief: "Charlie",
            year: 1999
        }, {
            chief: "Alice",
            year: 1979
        }]
    }, ];

    data.forEach(function(d) {
        d.values.sort(function(a, b) {
            return d3.ascending(+a.year, +b.year)
        });
    });

    console.log(data);
<script src="https://d3js.org/d3.v4.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.