0

What I need to do is to replace number by name based on data in array or object. I know how to do that in PHP.

This is the PHP code:

<?php
$array1 = array('111', '222', '333');
$array2 = array('john','adam','mike');

echo $array2[array_search('222', $array1)];

http://sandbox.onlinephpfunctions.com/code/599c839dccf5b3d9101cec2a45d14fc4bce258b1

And what I need is the same in JavaScript.

var numbers = ['111', '222', '333'];
var names = ['john','adam','mike'];
var something['222']=  .... ?
2
  • Can you edit to describe your problem more? How do numbers map to names? Commented Mar 2, 2021 at 14:56
  • I want to ask for '222' and reveive 'adam' in return Commented Mar 2, 2021 at 14:56

2 Answers 2

1
var numbers = ['111', '222', '333'];
var names = ['john','adam','mike'];

function rep (val) {
   let i = numbers.indexOf(val)
   return names[i]
}
Sign up to request clarification or add additional context in comments.

Comments

1

It looks like you need to create a map of numbers to names. You have a few options, but the shortest would be with a reduce:

const converted = array1.reduce(( acc,curr,index) => ({...acc, [curr]:array2[index]}), {})

const numbers = ['111', '222', '333'];
const names = ['john','adam','mike'];

const converted = numbers.reduce(( acc,curr,index) => ({...acc, [curr]:names[index]}), {})

console.log(converted['222']) // -> 'adam'

1 Comment

Hello Will, thanks, this also works, but "codeR developR" answer was easier for me. Thank you for contribution

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.