-1

I want to find data by value, but the value is an array .. how?

 mylokasi [
    {
        id: 1 ,
            name : koko
    },
    {
        id: 2 ,
            name : doni
    },
    {
        id: 3 ,
            name : dika
    },
    {
        id: 4 ,
            name : ujang
    },
    ]

    mylokasi.find(p => p.id== [2,3,4,3]).name

I want to display all the data in the array [2,3,4,3]

result value so : doni,dika,ujang,dika

4
  • Loop the array, and grab the object property from the array index for example myLokasi[0].id would be valid, obviously many ways to achieve the desired result. a loop is just one. Commented Jan 26, 2022 at 4:50
  • can give an example? Commented Jan 26, 2022 at 4:52
  • [2,3,4,3].map(id => mylokasi.find(e => e.id == id).name) also I want to mention that qontol==penis in indonesia language idk why this guy use it as name example Commented Jan 26, 2022 at 5:04
  • let arrr = mylokasi.map((item) => item.name) gives you new array like ['koko', 'doni', 'dika', 'qotol'] Commented Jan 26, 2022 at 5:05

2 Answers 2

5

You can use the filter and map functions:

mylocasi
  .filter(item => [2, 3, 4, 3].includes(item.id))
  .map(item => item.name)
Sign up to request clarification or add additional context in comments.

5 Comments

@Harry Wardana, this guy beat me to it. but this is an example aswell
It's worth noting that in JavaScript indices start at 0, so 1 is actually the second item
Better off actually comparing the id field instead of assuming the id equals to array index + 1. By designing an id field probably means that the array may not necessarily be sorted and continuous.
Very good point. I've updated my answer to reflect this. Thanks @RickyMo
But your updated answer isn't doing what OP want. Please check OP's expected output result.
2

Using map() and find() you can achieve your goal !

Try this code it's help you !

  let mylokasi = [{ id: 1, name: 'koko' }, { id: 2, name: 'doni' }, { id: 3, name: 'dika' }, { id: 4, name: 'qotol' }];
    let arr = [2, 3, 4, 3];
    let res = arr.map((id) => (mylokasi.find(x => x.id == id).name));
    console.log(res, '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.