【问题标题】:How it is possible to filter sentences in an array by another array of words?如何通过另一个单词数组过滤数组中的句子?
【发布时间】:2017-11-29 04:02:38
【问题描述】:

任务

构建一个为我们的聊天应用程序提供内容过滤的服务。 该服务应侦听传入消息的 firebase 引用子“/messages”。对于写入此子项的每条消息,您都需要过滤消息并用 firebase 数据库中“/words”引用子项中的“*”替换单词。

第 1 部分 - 在屏幕上的 /messages 中列出所有消息。

第 2 部分 - 列出屏幕上 /words 处的所有单词。

第 3 部分 - 编写一个算法,将 /words 列表中的单词更改为 ****,如果它们出现在来自 /messages 的任何消息中。

import React, { Component } from 'react';
import * as firebase from 'firebase';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: [],
      words: [],
      filterMessages: [],
    };
    console.log(this.state.messages, this.state.words);
  }

  componentWillMount() {
    const messages = firebase.database().ref().child('/messages');
    const words = firebase.database().ref().child('/words');
    console.log(messages, words);
    const messagesArray = [];
    const wordsArray = [];
    messages.on('child_added', snap => {
      messagesArray.push(snap.val());
      this.setState({
        messages: messagesArray,
      });
    });
    words.on('child_added', snap => {
      wordsArray.push(snap.val());
      this.setState({
        words: wordsArray,
      });
    });
  }

  filterByWords = () => {

  };

  filterData = (data) => data.filter(this.filterByWords);

  renderListItem = (data) => data.map((item, index) => {
    return (
      <li key={index}>{item}</li>
    )
  });


  render() {
    return (
      <div className="App">
        {console.log('render', this.state)}
        <ul className="defaultList">
          {this.renderListItem(this.state.messages)}
        </ul>
        <button
          className="filterBtn"
          onClick={() => this.filterData(this.state.messages)}
        >
          filter
        </button>
        <ul className="filterList">
          {this.renderListItem(this.state.filterMessages)}
        </ul>
      </div>
    );
  }
}

export default App;

【问题讨论】:

  • Array.filterArray.includes 是你的朋友。通过检查禁用词数组中是否存在来过滤句子数组。
  • 是的)我明白,但我不知道如何过滤优惠中的单词。

标签: javascript reactjs firebase filter firebase-realtime-database


【解决方案1】:
    const messageWords = message.split(" ");
    const newWords = words.map(word => messageWords.includes(word) ? "*".repeat(word.length) : word);

这可能是关于什么会起作用的一般概念 - 取决于您的数据是什么样的。

基本上,对于每条消息,您需要将该消息拆分为单词,以便您可以将 /words 与单个消息单词进行比较。然后只需使用 Array.prototype.includes 查找消息是否包含单词即可。如果匹配则返回“*”乘以单词的长度,否则只返回单词;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2021-12-22
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多