Loolii
Loolii

Reputation: 455

How can i make a new array easily?

I wanna make a new array consist of a name element.

let list = [
  [['firstName', 'Mary'],['lastName', 'Jenkins']],
  [['lastName', 'Kim']],
  [['firstName', 'Joe']]
];

I wanna extract the name value in this array, and return it to be like that

['Mary Jekins','Kim','joe'] // i want make it

How can I make it easy? apparently, I ever tried recursion But I faced another difficulty. if I pushed the element to a new array, it going to be like that.

['Mary','Jekins','Kim','Joe'] // i don't want it.

How to treat well? I need some tips.

Upvotes: 1

Views: 127

Answers (6)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14218

How to treat well? I need some tips.

Yes, You can use Array#map combined with Array#reduce like this

let list = [ [["firstName", "Mary"],["lastName", "Jenkins"]],
             [["lastName", "Kim"]],
             [["firstName", "Joe"]]];

const names = list.map(array => 
                  array.reduce((acc, [_, value]) => acc += ` ${value}`, '').trim());
console.log(names);

Output:

[
  "Mary Jenkins",
  "Kim",
  "Joe"
]

Upvotes: 0

Loránd Péter
Loránd Péter

Reputation: 314

You could try this with a forEach:

const list = [
  [['firstName', 'Mary'], ['lastName', 'Jenkins']],
  [['lastName', 'Kim']],
  [['firstName', 'Joe']]
];
const newList = []
list.forEach(person => {
  if (person.length == 1) {
    newList.push(person[0][1]);
  }
  if (person.length == 2) {
    newList.push(person[0][1] + ' ' + person[1][1]);
  }
});

console.log(newList)

But I would suggest you to use an other datastructure, if it's possible. It's more clear:

const list = [
  {firstName: 'Mary', lastName: 'Jenkins'},
  {lastName: 'Kim'},
  {firstName: 'Joe'}
];

Upvotes: 1

Beshambher Chaukhwan
Beshambher Chaukhwan

Reputation: 1448

This is a simple solution where I iterate the first level by Array.map() and then for the 2nd level of iteration I simply check if the name array has name element pair or not. Since the structure is storing key value pairs in form of arrays so its safe to omit the first element in each, assuming that its either of the key.

let list = [
  [['firstName', 'Mary'],['lastName', 'Jenkins']],
  [['lastName', 'Kim']],
  [['firstName', 'Joe']]
];

let newList = list.map(name => {
   let n = name.length>0 ? name[0][1] : ''; //take the first name value pair
   n+=' '+(name.length>1 ? name[1][1] : ''); // append space and 2nd name value pair
   return n.trim(); //trim the full name in case we didn't have full name
});

console.log(newList);

https://ideone.com/KQfYDF

Upvotes: 2

Garud Pragati
Garud Pragati

Reputation: 173

const namesArr = [];
for (let item of list) {
 const [first, second] = item;
 const [key, value] = first || ["", ""];
 const [key1, value1] = second || ["", ""];
 namesArr.push(`${value} ${value1}`);
}
console.log(namesArr); 

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074385

I think I'd use a map, and in the map callback turn those sub-arrays into objects, then build the output string from the object properties; destructuring the object gives me a convenient moment to default either name if it's missing:

const names = list.map(entry => {
    const {firstName = "", lastName = ""} = Object.fromEntries(entry);
    return `${firstName} ${lastName}`.trim();
});

Live Example:

let list = [
    [["firstName", "Mary"],["lastName", "Jenkins"]],
    [["lastName", "Kim"]],
    [["firstName", "Joe"]]
];

const names = list.map(entry => {
    const {firstName = "", lastName = ""} = Object.fromEntries(entry);
    return `${firstName} ${lastName}`.trim();
});
console.log(names);

I'm using the object there just in case instead of [["firstName", "Mary"],["lastName", "Jenkins"]] you sometimes have [["lastName", "Jenkins"],["firstName", "Mary"]].

Upvotes: 8

hgb123
hgb123

Reputation: 14891

You could use map on each of the child list (here 3), and for each of the child list, map the value only and join them (or do anything else you want)

let list = [
  [
    ["firstName", "Mary"],
    ["lastName", "Jenkins"],
  ],
  [["lastName", "Kim"]],
  [["firstName", "Joe"]],
];

const res = list.map((l) => l.map(([_, value]) => value).join(" "));

console.log(res);

Upvotes: 3

Related Questions