[英]Filter Array that contains specific symbol or words in Javascript
您好,我想在過濾我的數組時尋求幫助,我有一個包含單詞的數組列表,但我想過濾掉帶有符號(“#”)的單詞以在數組上刪除
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);
};
首先req
數組應包含對象(當前語法不正確):
var req = [
{ symbol: 'test' },
{ symbol: '#test1' },
// ...
];
然后,您可以嘗試:
const filteredReq = req.filter(item => item.symbol.indexOf('#') === -1);
對於簡單的數組,可以使用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);
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)
您可以遍歷所有鍵。 但是,如果多次使用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));
更好地使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.