mmt zyx mmt zyx - 2 months ago 32
Javascript Question

{nativescript} indexOf array

I have an array like below. When I using

this.itemsgroupcustomer.indexOf("Perorangan")
, it return -1. I don't have any idea why this is wrong. Please help.

viewModel.itemsgroupcustomer = [
{title: "Perusahaan"},
{title: "Perorangan"}
];

Answer

Use Array.prototype.find instead, it returns the element that passes the test:

const arr = [
  {title: "Perusahaan"},
  {title: "Perorangan"}
]
console.log(arr.find(el => el.title === 'Perorangan'))

You can then use the return value to find its index on the array

const arr = [
  {title: "Perusahaan"},
  {title: "Perorangan"}
]
const filteredElement = arr.find(el => el.title === 'Perorangan')
console.log(arr.indexOf(filteredElement))


UPDATE:

As user @zerkms has pointed there's a built in method that does the above in a single step, it's Array.prototype.findIndex

const arr = [
  {title: "Perusahaan"},
  {title: "Perorangan"}
]
console.log(arr.findIndex(el => el.title === 'Perorangan'))