根据另一个数组的值显示数组的值

时间:2019-08-12 08:04:09

标签: javascript arrays lodash

我有两个数组

     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' },
      ],

我想显示基于arry1的文本,并用逗号分隔,如下所示:

example1,example2,example3

我该如何实现?

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

3 个答案:

答案 0 :(得分:1)

您可以map遍历arr1中的每个元素来find中的对象arr2,并使用join创建一个逗号分隔的字符串。

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(','))

另一种方法是将reduceincludes一起使用:

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(','))

  

注意:第一种方法将基于arr1的顺序,而第二种方法将基于arr2

根据此JSPerf,最有效的方法是使用第一个解决方案:

JSPerf

答案 1 :(得分:1)

您可以过滤array2并映射所需的属性。

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

答案 2 :(得分:1)

您可以将array2简化为键/值对的对象,以便可以使用存储在value上的数字来检索text,如下所示:

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