排序数组的数组

时间:2017-09-09 10:18:43

标签: javascript arrays sorting

我目前有一个数组数组。我想根据其中一个数组中的日期值对其进行排序。例如,

这是我得到的数组,

arrayOfArray = [
  ["Date", "01/02/2017", "02/02/2016"],
  ["Temperature", "19", "16"],
  ["Humidity", "80%", "86%"]
]

我希望以这种方式排序:

newArrayOfArray = [
  ["Date", "02/02/2016", "01/02/2017"],
  ["Temperature", "16", "19"],
  ["Humidity", "86%", 80%"]
]

我想根据日期数组对数组进行排序,最新的第一个。 我怎样才能实现这一目标?提前谢谢。

5 个答案:

答案 0 :(得分:2)

基本上,您可以使用sorting with map并将所需的数组作为模式进行排序并重新生成数组。

var array = [["Date", "01/02/2017", "02/02/2016"], ["Temperature", "19", "16"], ["Humidity", "80%", "86%"]],
    selected = array[0],
    temp = selected.slice(1).map(function (_, i) { return i + 1; });
    
temp.sort(function (a, b) {
    function getISO(d) { return d.replace(/(..)\/(..)\/(....)/, '$3-$2-$1'); }
    return getISO(selected[a]).localeCompare(getISO(selected[b]));
});

temp.unshift(0);
array = array.map(function (a, i) {
    return temp.map(function(index){
       return array[i][index];
    });
})

console.log(array);

答案 1 :(得分:1)

你可以将它减少到另一个数组,在从第一个索引开始排序值的同时推送它。



   ObjectMapper mapper = new ObjectMapper();
    JacksonAnnotationIntrospector ignoreJsonTypeInfoIntrospector = new JacksonAnnotationIntrospector() {
        @Override
        protected TypeResolverBuilder<?> _findTypeResolver(
                MapperConfig<?> config, Annotated ann, JavaType baseType) {
            if (!ann.hasAnnotation(JsonTypeResolver.class)) {
                return super._findTypeResolver(config, ann, baseType);
            }
            return null;
        }
    };
    mapper.setAnnotationIntrospector(ignoreJsonTypeInfoIntrospector);
&#13;
&#13;
&#13;

我采用Nina's let arr = [ ["Date", "01/02/2017", "02/02/2016"], ["Temperature", "19", "16"], ["Humidity", "80%", "86%"] ]; function getISO(d) { return d.replace(/(..)\/(..)\/(....)/, '$3-$2-$1'); } let m = arr.reduce((a, b) => { let [n, ...rest] = b; if (n === 'Date') { rest.sort((x, y) => Date.parse(getISO(x)) - Date.parse(getISO(y))); } else { rest.sort((x, y) => parseInt(x) - parseInt(y)); } a.push([n, ...rest]); return a; }, []); console.log(m);方法使getISO在每个环境中都能正常工作。

答案 2 :(得分:0)

您的数据结构不是最佳排序方式。可以将其更改为每个日期的数据结构:

var dataPerDate = [];
var [dates,temp,humidity] = arrayOfArrays;
dates.forEach((date,i)=>{
  if(!i) return;
  dataPerDate.push({
    date,
    temp:temp[i],
    humidity:humidity[i]
  };
});

所以现在你可以轻松地对它进行排序:

dataPerDate.sort(
 (a,b)=>new Date(a.date) - new Date(b.date)
);

答案 3 :(得分:0)

这是一种适应MDN's recommendation for using map() in sort()的方法:

let arrayOfArrays = [
  ["Date", "01/02/2017", "02/02/2016"],
  ["Temperature", "19", "16"],
  ["Humidity", "80%", "86%"]
]

function sortByDate(outer) {
  const [ [label, ...values], ...rest ] = outer
  const dates = values.map((value, index) => {
    // convert date string to number
    const time = Date.parse(value.replace(/(..)\/(..)\/(....)/, '$3-$2-$1'))
    
    // map object to remember original index and value
    return { time, index, value }
  }).sort((a, b) => a.time - b.time)
  
  // return sorted dates with other subarrays re-ordered dependently
  return [
    [
      label,
      ...dates.map(date => date.value)
    ],
    ...rest.map(([label, ...inner]) => [
      label,
      ...inner.map((value, index) => inner[dates[index].index])
    ])
  ]
}

console.log(sortByDate(arrayOfArrays))

答案 4 :(得分:-1)

您可能需要考虑使用数据对象并编写自己的排序函数来对此对象的日期进行排序,如下所示:

&#13;
&#13;
var Datapoint = function (date, temp, humidity) {
  this.date = date;
  this.temp = temp;
  this.humidity = humidity;
};

var array = [
  new Datapoint(new Date(2017, 1, 1), 19, 80),
  new Datapoint(new Date(2016, 1, 2), 16, 86),
  new Datapoint(new Date(2017, 0, 2), 13, 88),
  new Datapoint(new Date(2017, 1, 1), 21, 76)
];

array.sort(function (a, b) {
  return a.date > b.date ? 1 : a.date < b.date ? -1 : 0;
});

// Just for representation
Datapoint.prototype.toString = function () {
  var dateString = this.date.getDate() + "/" + (this.date.getMonth() + 1) + "/" + this.date.getFullYear();
  return "Date: " + dateString + ", temperature: " + this.temp + "&deg;, humidity: " + this.humidity + "%";
};

document.getElementById("result").innerHTML = array[0].toString() + "<br/>" + array[1].toString() + "<br/>" + array[2].toString() + "<br/>" + array[3].toString();
&#13;
<div id="result"></div>
&#13;
&#13;
&#13;