包含Java中特定符号或单词的过滤器数组

时间:2018-07-19 07:14:21

标签: javascript arrays

您好,我想在过滤我的数组时寻求帮助,我有一个包含单词的数组列表,但我想过滤掉带有符号(“#”)的单词以在数组上删除

function InitializeV3() {
    var req = SymbolList; //obj with symbol property
    for (var i = 0; i < req.lenght; i++) {
        if (req[i].smybol.includes("#")) {
            req.splice(req[i], 1);
        }
    }
    console.log(req);
};

5 个答案:

答案 0 :(得分:0)

首先-req数组应包含对象(当前语法不正确):

var req = [
 { symbol: 'test' },
 { symbol: '#test1' },
 // ...
];

然后您可以尝试:

const filteredReq = req.filter(item => item.symbol.indexOf('#') === -1);

答案 1 :(得分:0)

对于一个简单的数组,您可以使用filter方法这样做:

var req = ['test','#test1','#test2','test3','test4'];

var result = req.filter(item => !item.includes("#"));

console.log(result);

如果您有对象数组:

var req = [{symbol: 'test'},{symbol: '#test1'},{symbol: '#test2'},{symbol: 'test3'},{symbol: 'test4'}]
    
var result = req.filter(item => !item.symbol.includes('#'));

console.log(result);

答案 2 :(得分:0)

function InitializeV3() {
  // For simple array
  var req = ['test',
    '#test1',
    '#test2',
    'test3',
    'test4'
  ]
  var filtered = req.filter(item => !item.includes('#'))
  console.log(filtered)
};

InitializeV3();

// For array of objects
var req = [{
  symbol: 'test'
}, {
  symbol: '#test1'
}, {
  symbol: '#test2'
}, {
  symbol: 'test3'
}, {
  symbol: 'test4'
}]

// Use the following
var filtered = req.filter(item => !item.symbol.includes('#'))
console.log(filtered)

答案 3 :(得分:0)

您可以遍历所有键。但是,如果多次使用symbol作为密钥,则只会保存最后的数据。

let SymbolList = {
    symbol0:'test',
    symbol1:'#test1',
    symbol2: '#test2',
    symbol3:'test3',
    symbol4: 'test4'
  };

function InitializeQuotesV3(req) {
  for (key in req) {
    req[key] = req[key].replace(/#/g,"");
  }
  return req;
};

console.log(InitializeQuotesV3(SymbolList));

答案 4 :(得分:0)

更好地使用JS Regex Regex

    var req = [{symbol:'test'} ,
           {symbol:'#test1'},
           {symbol: '#test2'}, 
           {symbol:'test3'} ,
           {symbol: 'test4'}];
          let hasHash = /#/;
        for (var i = req.length - 1; i >= 0; i--) {
            if (hasHash.test(req[i].symbol)) {
                req.splice(i,1); 
            }
        }
        console.log(req);