-1

Now I have array like this:

let arr = [{
    name: 'Tony', age: 17, love: [1, 2, 4]
}, {
    name: 'David', age: 12, love: [6, 6, 6]
}, {
    name: 'John', age: 10, love: [0, 0, 0]
}]

And I want to map this array and get result

const a1 = arr.map(man => {
    if(man.name === 'Tony') {
        for(let i = 0; i < man.love.length; i++) {
            return man.love[i]
        }
    }
    else {
        return man.name
    }
})

The result I want is [ 1, 2, 4, 'David', 'John' ].

But I got [ 1, 'David', 'John' ].

How can I achieve that?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Real
  • 1
  • 1
  • 2
    A map will return exactly as many outputs as you have inputs. You want a *reduce* or a plain old loop. – deceze Feb 16 '22 at 07:51
  • Get familiar with [how to access and process objects, arrays, or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Feb 16 '22 at 07:58

2 Answers2

4

What you need is flatMap. It allows you to return arrays which will then be flattened.

let arr = [{
    name: 'Tony', age: 17, love: [1, 2, 4]
}, {
    name: 'David', age: 12, love: [6, 6, 6]
}, {
    name: 'John', age: 10, love: [0, 0, 0]
}]

const a1 = arr.flatMap(man => {
    if(man.name === 'Tony') {
        return man.love
    }
    else {
        return man.name
    }
})

console.log(a1);
lusc
  • 1,206
  • 1
  • 10
  • 19
-1

it is rather necessary to make the loop with man.love.length

const a1 = arr.map(man => {
    if(man.name === 'Tony') {
        for(let i = 0; i < man.love.length; i++) {
            return man.love
        }
    }
    else {
        return man.name
    }
})
Nagini
  • 1
  • 2