0

How to get the index of an array? Now I get undefined as the result of executing the "blockCreate" function, I think this is because I do not specify the index of the array, although I should get true, how to automatically indicate the index for the array?

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [array1, setArray1] = useState([{ number: 1 }]);
  const [array2, setArray2] = useState([{ number: 2 }]);

  const blockCreate = () => {
    return array1.find(items => {
      const bool = array2.find(i => i.number === items.number);
      console.log(bool);
    });
  };

  return (
    <div className="App">
      <div>{blockCreate()}</div>
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

6
  • Tell us more about what exactly you are trying to build. What blockCreate() is supposed to do, in particular? Commented Jan 31, 2020 at 23:40
  • The array1.find function should return true or false Commented Jan 31, 2020 at 23:45
  • I want to get true, but I get undefined Commented Jan 31, 2020 at 23:46
  • find returns undefined when there is nothing found. The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned. Commented Jan 31, 2020 at 23:50
  • Array.find() doesn't return a boolean, instead it return the first element that matches the condition. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 31, 2020 at 23:51

1 Answer 1

2

Array.find() doesn't return a boolean, instead it return the first element that matches the condition. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

It's quite obscure what you're trying to do, but I think what you looking for is Array.some() which return a boolean. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.