検索

JAVASCRIPT
/* search function */
function searchResults(data, word, opt){
    if(!word) return;

    let words = (word)? word.split(/,|、|\s| /): null;
    let merged = [];
    let results = [];
    let obj = {};
    let resultJson = [];

    for(let i in data){
        merged = merged.concat(data[i].qalist);
    }

    //OR
    let searchWord = function(s){
        let res = merged.filter(function(item, index){
            if(item['q'].indexOf(s) !== -1 || item['a'].indexOf(s) !== -1 || item['kwd'].indexOf(s) !== -1) return true;
        });
        return res;
    }

    words.forEach(function(w){
        let re = searchWord(w);
        results = results.concat(re);
    });

    //AND
    let searchAndresult = function(s){
        let temp = [];
        for(let i=0; i<s.length; i++){
            let sdata = (i == 0)? merged : temp[i-1];
            temp[i] = sdata.filter(function(item, index){
                if(item['q'].indexOf(s[i]) !== -1 || item['a'].indexOf(s[i]) !== -1 || item['kwd'].indexOf(s[i]) !== -1) return true;
            });
        }
        let res = temp[s.length-1];
        return res;
    }

    if(opt == 'and') results = searchAndresult(words);

    /* 重複削除 */
    results = results.filter(function(item, index, self){
        return self.findIndex((e) => e.id === item.id) === index;
    });
    obj.cname = '検索結果: ' + results.length + '件';
    obj.types = words;
    obj.qalist = results
    resultJson.push(obj);
    return resultJson;
}
Copied title and URL