如何在javascript中将一个数组拆分为两个数组?

问题描述 投票:0回答:6

我有一个数组

var plans=[a, b, c, d ];
,其价格每年每月一次。

Consider- a and b are monthly and c and d are yearly.

所以,我想根据每月和每年的值拆分数组,并将这些值存储到单独的数组中

var monthly_plans=[]; and  var yearly_plans=[]

那么,我该怎么做呢?

我之前使用过 js

split()
函数,但只是非常基础的水平。

javascript arrays for-loop
6个回答
4
投票

split()
String
对象的方法,而不是
Array
对象的方法。

根据我对你问题的理解,你需要

Array.prototype.slice()
方法:

slice() 方法返回数组的一部分的浅拷贝 到一个新的数组对象中。

语法

arr.slice([begin[, end]])

总之,您可能想做这样的事情:

var monthly_plans = plans.slice(0, 2);
var yearly_plans = plans.slice(2);

3
投票

您可以在数组上使用

slice(start, end)
函数,例如

monthly_plans = plans.slice(0,2);
yearly_plans = plans.slice(2,4);

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice


2
投票

ES5 方法:

var plans=[a, b, c, d];

var monthly_plans = plans.filter( plan => plan==='monthly condition' );
var yearly_plans = plans.filter( plan => plan==='yearly condition' );

1
投票

我认为使用

for
将是更好的途径。

示例:

for (var i=0;i<plans.length;i++)
{
  if(plans[i] == 'monthly condition')
  {
     monthly_plans.push(plans[i]);
  }
  else
  {
     yearly_plans.push(plans[i]);
  }
}

1
投票

根据您的帖子,解决方案不会涉及

split()
。如果您提前知道哪些计划指定是每月的,哪些是每年的:

var plans = ['a', 'b', 'c', 'd', 'm', 'y', ....... 'n'],
    count = plans.length, i = 0;

var monthly_designations = ['a', 'b', 'm'],
    yearly_designations = ['c', 'd', 'y'];

for(; i < count; i++) {

    if (monthly_designations.indexOf(plans[i]) !== -1) {
        monthly_plans.push(plans[i]);
    } else {
        if (yearly_designations.indexOf(plans[i]) !== -1) {
            yearly_plans.push(plans[i]);
        }
    }

}

然后只需根据已知的名称检查计划数组即可将内容过滤到正确的子数组中

monthly_plans
yearly_plans


0
投票

也许

function split2DAryOnIdx_n() {
  const 
    array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    [leftArray, rightArray] = split2DAryOnIdx(array, 1);

console.log(leftArray); // [[1], [4], [7]]
console.log(rightArray); // [[2, 3], [5, 6], [8, 9]]

}

const 
  split2DAryOnIdx = (array, Idx) => {
    let 
     leftArray  = [],
     rightArray = [];

    for (let row of array) {
      let 
        leftElement  = row.slice(0, Idx),
        rightElement = row.slice(Idx);

      leftArray.push(leftElement);
      rightArray.push(rightElement);    
  }

  return [leftArray, rightArray];
}
© www.soinside.com 2019 - 2024. All rights reserved.