Javascript删除数组中的每个其他数组

问题描述 投票:-1回答:3

我有一系列数组,我试图摆脱3月和9月。我一直在尝试下面的代码,但我没有得到任何输出。请提出我缺少的内容以及如何改进这一点。

//w is the data array    
for(var i = 0; i < w.length; i+=1)
       w.splice(i, 1);

 data: 
   [ [ '1983-03-31', 29.4, 29.6, 29.25, 29.29],
     [ '1983-06-30', 31.25, 31.4, 31.25, 31.38],
     [ '1983-09-30', 30.53, 30.55, 30.2, 30.36],
     [ '1983-12-31', 29.66, 29.8, 29.36, 29.6],
     [ '1984-03-31', 30.83, 30.85, 30.74, 30.85]]
javascript arrays node.js
3个回答
1
投票

您可以使用filter功能

var data =   [ [ '1983-03-31', 29.4, 29.6, 29.25, 29.29],     [ '1983-06-30', 31.25, 31.4, 31.25, 31.38],     [ '1983-09-30', 30.53, 30.55, 30.2, 30.36],     [ '1983-12-31', 29.66, 29.8, 29.36, 29.6],     [ '1984-03-31', 30.83, 30.85, 30.74, 30.85]];
     
var result = data.filter(([date]) => {
  var [_, month] = date.split('-');
  return month !== '09' && month !== '03';
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

或者你可以遵循slice方法

var data =   [ [ '1983-03-31', 29.4, 29.6, 29.25, 29.29],     [ '1983-06-30', 31.25, 31.4, 31.25, 31.38],     [ '1983-09-30', 30.53, 30.55, 30.2, 30.36],     [ '1983-12-31', 29.66, 29.8, 29.36, 29.6],     [ '1984-03-31', 30.83, 30.85, 30.74, 30.85]];
     
     
for (var i = 0; i < data.length; i++) {
  var [date] = data[i];
  var [_, month] = date.split('-');
  if (month === '09' || month === '03') {
    data = data.slice(0, i).concat(data.slice(i + 1, data.length));
  }
}

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0
投票

我同意Ele的答案,即filter是这样做的方式,而在另一方面:如果你已经知道阵列总是带有3月1日,6月,9月,12月等,那么你可以使用数组内元素的索引,以确定是否要保留元素。这回答了“删除所有其他元素”的问题,而不是您的问题机构“删除3月和9月”的要求。

var data =   [ [ '1983-03-31', 29.4, 29.6, 29.25, 29.29],     [ '1983-06-30', 31.25, 31.4, 31.25, 31.38],     [ '1983-09-30', 30.53, 30.55, 30.2, 30.36],     [ '1983-12-31', 29.66, 29.8, 29.36, 29.6],     [ '1984-03-31', 30.83, 30.85, 30.74, 30.85]];
     
var result = data.filter((_, i) => {
  return i % 2 == 1;
});

console.log(result);

0
投票

你也可以使用.filter().every().includes()

let monthsToFilter = ['03', '09'];
let data = [
    ['1983-03-31', 29.4, 29.6, 29.25, 29.29],
    ['1983-06-30', 31.25, 31.4, 31.25, 31.38],
    ['1983-09-30', 30.53, 30.55, 30.2, 30.36],
    ['1983-12-31', 29.66, 29.8, 29.36, 29.6],
    ['1984-03-31', 30.83, 30.85, 30.74, 30.85]
];
     
let result = data.filter(([date]) => {
    return monthsToFilter.every(m => !date.includes('-' + m + '-'));
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

有用的资源:

© www.soinside.com 2019 - 2024. All rights reserved.