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);
};
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);
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);
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)
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));
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.