Joemar Zeta
Joemar Zeta

Reputation: 53

Filter Array that contains specific symbol or words in Javascript

Hello I would like to ask for help on filtering my Array currently I have a list of array that contains words but I want to filter out those with symbol ("#") to be remove on the array

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);
};

Upvotes: 2

Views: 25321

Answers (5)

Senthur Deva
Senthur Deva

Reputation: 787

Better you can use 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);

Upvotes: 0

TessavWalstijn
TessavWalstijn

Reputation: 1726

You can loop over all the keys. But if you have symbol multiple times as key only the last data will be saved.

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));

Upvotes: 0

codejockie
codejockie

Reputation: 10864

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)

Upvotes: 1

Giannis Mp
Giannis Mp

Reputation: 1299

For a simple array you can do it like this with the filter method:

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

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

console.log(result);

And if you have an array of objects:

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

console.log(result);

Upvotes: 3

hsz
hsz

Reputation: 152216

First of all - req array should contain objects (current syntax is incorrect):

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

Then you can try with:

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

Upvotes: 0

Related Questions