比较两个数组中的值并生成一个新数组

我有两个数组,它们可能有也可能没有相似的值


const arrayOne = [orange, red, black, blue, yellow]

const arrayTwo = [blue, purple, white, red]

我正在使用react,useEffect我希望在通过它进行某些更改时onClick返回不相同的值


例子:-


const = [orange, purple, black, white, yellow]

我已经尝试过以下...


const [newArray, setNewArray] = useState([])

const [reload, setReload] = useState(false)


  useEffect(() => {

    const results = arrayOne.filter((i) => {

      return (

        i.id != arrayTwo.id

      )

      setNewArray(results)

    })

  }, [reload])


  return (

    <button onClick={() => setReload(!reload) }>

      Trigger useEffect

    </button>

  )


aluckdog
浏览 143回答 4
4回答

长风秋雁

找到相似的项目,然后进行相应的过滤:const arrayOne = ['orange', 'red', 'black', 'blue', 'yellow']const arrayTwo = ['blue', 'purple', 'white', 'red']// [red,blue]const dupItems = arrayOne.filter(item => arrayTwo.includes(item));const output = [...arrayOne.filter(item => !dupItems.includes(item)), ...arrayTwo.filter(item => !dupItems.includes(item))];console.log(output);

鸿蒙传说

也许这样的事情可以工作const diffArray = arrayOne.reduce((acc, value) => {&nbsp; if ((arrayTwo.inclues(value) { return acc; }&nbsp; return acc.concat([value]);}, []);注意:请检查我的代码中是否有拼写错误,我是通过手机接听的

Qyouu

尝试这个function diff (a1, a2) {&nbsp; &nbsp; var a = [], diff = [];&nbsp; &nbsp; for (var i = 0; i < a1.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; a[a1[i]] = true;&nbsp; &nbsp; }&nbsp; &nbsp; for (var i = 0; i < a2.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (a[a2[i]]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; delete a[a2[i]];&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[a2[i]] = true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; for (var k in a) {&nbsp; &nbsp; &nbsp; &nbsp; diff.push(k);&nbsp; &nbsp; }&nbsp; &nbsp; return diff;}// call here&nbsp;diff( ['a', 'b'], ['a', 'b', 'c', 'd'] );

隔江千里

一种解决方案是这样做:let arrayOne=['orange', 'red', 'black', 'blue', 'yellow'];let arrayTwo=['blue', 'purple', 'white', 'red'];let common=arrayOne.filter(value => arrayTwo.includes(value))let result=[...new Set([...arrayOne,...arrayTwo])].filter(value=>common.indexOf(value)==-1)console.log(result)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript