2

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.

3
  • 1
    map then find? Commented Feb 25, 2020 at 22:55
  • There is no built in function, you will have to wrap your first example in a custom function. Commented Feb 25, 2020 at 22:56
  • There's Array.findIndex() that would reduce some effort Commented Feb 25, 2020 at 22:58

2 Answers 2

3

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);

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

1 Comment

Pretty similar to @jonrsharpe's map suggestion. I'm sure there are many ways to skin this cat but I was mainly just wondering if a single function similar to what I described existed. Seems not. Wonder if it'd be anything worth adding to the spec.
0

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));

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.