Array.find() or Array.some() but return a custom value

Viewed 2551

What I can do:

const val = array.find((val) => <condition>);
const index = array.indexOf(val);

What I'd like to do:

const { val, index } = array.someFunc((val, index) => <condition> && { val, index });

Anything like this out there? some() is reduced to a boolean, and find() just returns the array element, but neither fit the use case.

2 Answers

There's no built-in for this. But Object.entries could be used:

const array = ['foo', 'bar', 'baz'];

const [ index, val ] = Object.entries(array).find(([i, v]) => v === 'baz');

console.log(index, val);

There is no built in prototype to do that for an array, so you will need to create a wrapper function.

let numbers = [10, 20, 30, 40, 50];

function myFunction(array, find) {
  const val = array.find((val) => find == val);
  const index = array.indexOf(val);
  return { val, index };
}

console.log(myFunction(numbers, 30));

Most people's least favorite option is to extend Array.prototype, so you can call the function array.myFunction(40)

let numbers = [10, 20, 30, 40, 50];

Array.prototype.myFunction = function(find) {
  const val = this.find((v) => find == v);
  const index = this.indexOf(val);
  return { val, index };
}

console.log(numbers.myFunction(30));

Related