0

I have two arrays

     var arry1 = [1,2,3]
     var array2 = [
        { value: 1, text: 'example1' },
        { value: 2, text: 'example2' },
        { value: 3, text: 'example3' },
        { value: 4, text: 'example4' },
        { value: 5, text: 'example5' },
      ],

i want to display the text based on arry1 delimited by commas something like below:

example1,example2,example3

how do I achieve that ?

var x = arry2.forEach(function(element, value){
        if (element.value == arry1){
          return element.value
        }
      });

3 Answers 3

1

You could filter array2 and map the wanted property.

var array1 = [1, 2, 3],
    array2 = [{ value: 1, text: 'example1' }, { value: 2, text: 'example2' }, { value: 3, text: 'example3' }, { value: 4, text: 'example4' }, { value: 5, text: 'example5' }],
    result = array2
        .filter(({ value }) => array1.includes(value))
        .map(({ text }) => text);

console.log(result);

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

Comments

1

You can reduce your array2 to an object of key-value pairs so that you can use the number stored at value to retrieve your text like so:

const array1 = [1, 2, 3]
const array2 = [{value: 1, text: 'example1'}, {value: 2, text: 'example2'}, {value: 3, text: 'example3'}, {value: 4, text: 'example4'}, {value: 5, text: 'example5'}];

const lut = array2.reduce((a, {value, text}) => ({...a, [value]:text}), {});
const res = array1.map(num_key => lut[num_key]).join() // loop through each number and then display it's associated text from the look-up-table we generated
console.log(res);

1 Comment

From my understanding, this solution has the best time complexity with O(n + m). Iterating while calling includes or indexOf on every step of an iteration like in other solutions comes around with O(n * m). This doesn't matter for small arrays like in this example but depending on the real data it might.
0

You can map through each element in arr1 to find the object in arr2, and use join to create a comma delimited string.

var arr1 = [1, 2, 3]
var arr2 = [{value: 1,text: 'example1'},{value: 2,text: 'example2'},{value: 3,text: 'example3'},{value: 4,text: 'example4'},{value: 5,text: 'example5'}]

console.log(arr1.map(v => arr2.find(o => o.value === v).text).join(','))

Another way would be to use reduce with includes:

var arr1 = [1, 2, 3]
var arr2 = [{value: 1,text: 'example1'},{value: 2,text: 'example2'},{value: 3,text: 'example3'},{value: 4,text: 'example4'},{value: 5,text: 'example5'}]

console.log(arr2.reduce((a, {value, text}) => (arr1.includes(value) && a.push(text), a), []).join(','))

NOTE: The first method will base the ordering from arr1, while the second method will base the ordering on arr2

The most efficient way, would be to use the first solution, according to this JSPerf:

JSPerf

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.