1

I have a javascript array like this:

const IMGS = [{
    id: 0,
    path: "../img/a1.jpeg",
  },
  {
    id: 1,
    path: "../img/a1-01.jpeg",
  },
  {
    id: 2,
    path: "../img/a1-02.jpeg",
  },
  {
    id: 3,
    path: "../img/a1-03.jpeg",
  }
]
export default IMGS;

There are more images I am just showing few of them, I need to show all the images in react from this array. The condition is the image_id should be >=18 but <30. How can I achieve that? (I need to know the syntax).

I know I can do it using filter or map function, actually I'm new to javascript coming from c++, python background. It looks bit confusing to me. Please help! This is my react code where I'm rendering it

<React.Fragment>
      <Jumbotron>
          <img src={background} alt="Not loading"  id="jumbotron-image" className="img-fluid"/>
      </Jumbotron>
      <div className="container">
          <div className="row">
              <h1>Trending</h1>
          </div>
          <div className="row">
            {/*images go here*/}
          </div>
      </div>
  </React.Fragment>

2 Answers 2

1
 const IMGS = [
      {
        id: 0,
        src:require("../img/a1.jpeg"),
      },
      {
        id: 1,
        src: require("../img/a1.jpeg"),
      },
      {
        id: 2,
        src:require("../img/a1.jpeg"),
      },
      {
        id: 20,
        src:require("../img/a1.jpeg"),
      },
    ]
    const imgFilter= IMGS.filter((img) => img.id >= 18 && img.id < 30)

     {imgFilter.map(p => {
          return <img key={p.id} src={p.src} />;
        })}
Sign up to request clarification or add additional context in comments.

Comments

1

Use filter

const IMGS = [
  {
    id: 0,
    path: "../img/a1.jpeg",
  },
  {
    id: 1,
    path: "../img/a1-01.jpeg",
  },
  {
    id: 2,
    path: "../img/a1-02.jpeg",
  },
  {
    id: 20,
    path: "../img/a1-03.jpeg",
  },
]

const res = IMGS.filter((img) => img.id >= 18 && img.id < 30)

console.log(res)

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.