0

I have two arrays of strings and want to compare them by value and extract the index numbers of identical items of mainArray that are available in secondArray for example:

var mainArray = ["I", "am", "not", "a", "doctor"]
var secondArray = ["am", "doctor"]

var Result = [1,4]

2 Answers 2

1

you can use Array.prototype.indexOf()

const mainArray = ["I", "am", "not", "a", "doctor"];
const secondArray = ["am", "doctor"];
const result = secondArray.map(w => mainArray.indexOf(w));
console.log(result);

Note: This solution will return -1 for that cases when string doesn't match.

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

Comments

0

You can use intersection method of lodash library.

const mainArray = ["I", "am", "not", "a", "doctor"]
const secondArray = ["am", "doctor"]

const result = _.intersection(mainArray, secondArray)
const resultIndices = result.map(i => mainArray.indexOf(i))

console.log(result)
console.log(resultIndices)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

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.