0

I have two arrays

array1 = [
    {name: "samsung", views: 1200},
    {name: "apple", views: 200}
]

array2 = [
    {name: "samsung-1234", views: 200},
    {name: "apple-2332", views: 200},
    {name: "samsung-6543", views: 400},
    {name: "samsung-9876", views: 600}
]

How can I get sumsung has 3 types and apple has 1 type in array2.

Thanks. Any help is appreciated

1
  • Loop and count. Commented Aug 2, 2018 at 17:43

5 Answers 5

3

You can use .filter() on array2 and specify name from array1 to build the filter and .includes() to compare names

let array1 = [
    {name: "samsung", views: 1200},
    {name: "apple", views: 200}
];

let array2 = [
    {name: "samsung-1234", views: 200},
    {name: "apple-2332", views: 200},
    {name: "samsung-6543", views: 400},
    {name: "samsung-9876", views: 600}
];


let result = array1.map(x => ({ name: x.name, total: array2.filter(a => a.name.includes(x.name)).length }));

console.log(result);

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

Comments

1

You could take a map for counting the occurence and update array1.

var array1 = [{ name: "samsung", views: 1200 }, { name: "apple", views: 200 }],
    array2 = [{ name: "samsung-1234", views: 200 }, { name: "apple-2332", views: 200 }, { name: "samsung-6543", views: 400 }, { name: "samsung-9876", views: 600 }];
    types = new Map(array1.map(o => ([o.name, Object.assign(o, { types: 0 })])));
    
array2.forEach(({ name }) => ++types.get(name.split('-')[0]).types);

console.log(array1);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0
array1.map(el => {
    return array2.filter(el2 => {
        return el2.name.includes(el.name)
    })
})

Does it help you?

Comments

0

I'm not entirely sure I understand the significance of the first array, but you can get the number of items with Samsung with a simple for loop.

let cnt = 0;
array2.forEach((val) => {if (val.name.match(/samsung/i)) { cnt++}})
console.log(cnt) // 3

Comments

0

array1 = [
    {name: "samsung", views: 1200},
    {name: "apple", views: 200}
]

array2 = [
    {name: "samsung-1234", views: 200},
    {name: "apple-2332", views: 200},
    {name: "samsung-6543", views: 400},
    {name: "samsung-9876", views: 600}
]

const result = array1.map(brand => {
    let howManyTypes = array2.filter(ele =>  ele.name.indexOf(brand.name) != -1).length;
    return {name: brand.name, howManyTypes}
})

console.log(result)

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.