-4

I have two arrays;

let items = {
    search: [
       ['car', 'door', 'pen']
    ]
}

let data.props = [];

data.props = [
    {label: "car"}, 
    {label: "window"},
    {label: "kettle"},
    {label: "chair"},
    {label: "door"},
]

How can I check/compare between the two arrays using es6? A little bit tricky for me since items[] is a nested array.

What I have only checks for the first item.

if (data.props['0'].label === items.search['0'].values['0']) {
        let searchItems = [];
        searchItems.push(data.props['0']);
        console.log(searchItems);
    }
colin_dev256
  • 805
  • 2
  • 16
  • 36
  • 1
    What do you mean by "check/compare between the two arrays"? Please provide desired output and show your attempt to implement the requirement. – Yury Tarabanko Jul 23 '18 at 13:10
  • 1
    what are you aiming for? – messerbill Jul 23 '18 at 13:11
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output. – mplungjan Jul 23 '18 at 13:12
  • Your code is invalid JS. You cannot assign to data.props without having an object first and you should not quote array indicii – mplungjan Jul 23 '18 at 13:23
  • Your code is not more valid now after your edit. Please read up on array vs objects. `search: [ values: ['car', 'door', 'pen'] ]` is not a valid array entry. Create a snippet using `<>` and test it to make a [mcve] – mplungjan Jul 23 '18 at 13:37
  • thanks for the feedback all. I was rushing while creating this question - apologies for the edits here and there. I think I have the insight I need to solve my issue. – colin_dev256 Jul 23 '18 at 13:45

2 Answers2

0

You can use streams:

// if multiple search values:
const items = {
    search: {
        values: ['car', 'door', 'pen']
    }
}

let data = {
  props: []
};

data.props = [
    {label: "window"}, 
    {label: "car"},
    {label: "kettle"},
    {label: "chair"},
    {label: "door"},
];

let matches = data.props
  .map(prop => prop.label)
  .filter(prop => items.search.values.indexOf(prop) >= 0);
  
console.log(matches);

// if one search value

let searchItem = "car";

matches = data.props
  .map(prop => prop.label)
  .filter(prop => searchItem === prop);
  
console.log(matches);
Spitzbueb
  • 5,233
  • 1
  • 20
  • 38
0
let items = {
    search: {
        values: ['car', 'door', 'pen']
    }
}

let data = {
  props: [
        {label: "window"}, 
        {label: "car"},
        {label: "kettle"},
        {label: "chair"},
        {label: "door"},
    ]
}

console.log(data.props.filter(prop => items.search.values.indexOf(prop.label) >= 0));

log output is :

[0]: {label: "car"}
[1]: {label: "door"}
Seryoga
  • 793
  • 6
  • 15