分割最后两个单词并在javascript中过滤

时间:2019-04-09 01:46:28

标签: javascript jquery arrays string object

我想知道如何使用javascript过滤值数组 如何用“ provider-send”和“ provider-receive”分隔数组

 var filterradio = id.filter(function(e){       
       return e.id.split("-")[0] == "provider-send"
    })  
var id=["provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund"]


Expected Output:
result_sn: ["provider-send-credit-transfer", "provider-send-debit-fund"]
result_rcn:["provider-receive-credit-transfer","provider-receive-debit-fund"]

5 个答案:

答案 0 :(得分:1)

如果始终是“ provider-receive -...”和“ provider-send ...”,那么您可以执行以下操作将它们分开

for (i = 0; i < id.length; i++) {
    if (id[i].split("provider-send-").length > 1) {
        result_sn.push(id[i]);
    } else if (id[i].split("provider-receive-").length > 1) {
        result_rcn.push(id[i])
    }
}

答案 1 :(得分:0)

2作为第二个参数传递给split(),然后再次join()传递-split()的第二个参数指定结果数组中元素的最大数量。

var id=["provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund"]

var filterradio = id.filter(function(id){    
    return id.split("-",2).join('-') === "provider-send"
})  
         
 console.log(filterradio)

答案 2 :(得分:0)

我建议使用reduce代替filter,因为reduce用于将数组大小减小为单个返回的元素。 在这里,我将数组简化为具有两个键result_snresult_rcn的对象。

var id = ["provider-send-credit-transfer", "provider-send-debit-fund", "provider-receive-credit-transfer", "provider-receive-debit-fund"]


const result = id.reduce((obj, str) => {
  if (str.match(/^provider-send/g))
    obj['result_sn'].push(str);
  else
    obj['result_rcn'].push(str);
  return obj;
}, {
  'result_sn': [],
  'result_rcn': []
});

console.log(result)

答案 3 :(得分:0)

尝试一下:

var id = [ "provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund" ] ;

var result_sn = [] , result_rcn = [] ;

for( value of id ) {
  var twoWords = value.split('-',2).join('-') ;
  if ( twoWords === "provider-send" ) 
    result_sn.push( value ) ;
  else if ( twoWords === "provider-receive" )
    result_rcn.push( value ) ;
}

console.log( result_sn ) ;
console.log( result_rcn ) ;

答案 4 :(得分:0)

使用.filter()将要求您为每个要匹配的模式都分配一个变量来编写1个过滤器。

建议使用.reduce(),并且更易于扩展以支持更多模式。

乍一看可能令人生畏,但实际上您是在使用accumulator作为临时变量,该临时变量被存储并提交给每个迭代。数组的每次迭代都会为您提供currentValue的当前迭代值。

我添加了something-else作为添加新模式的示例。

var id = [
  "provider-send-credit-transfer",
  "provider-send-debit-fund",
  "provider-receive-credit-transfer",
  "provider-receive-debit-fund",
  "something-else-credit-transfer",
  "something-else-debit-fund"
];

const {
  'provider-send': result_sn,
  'provider-receive': result_rcn,
  'something-else': result_ste
} = id.reduce(function(accumulator, currentValue) {
  let prefix = currentValue.match(/^\w+-\w+/)[0];
  return {...accumulator, [prefix]: (accumulator[prefix] || []).concat(currentValue)}
}, {});

console.log(result_sn);
console.log(result_rcn);
console.log(result_ste);