Home > Software engineering >  JavaScript Removing anything after char in 2d array
JavaScript Removing anything after char in 2d array

Time:11-23

if I have data


    dogNames = [[]];

    dogNames.push([Bill],[Ben],[jack, Allen],[Barbra],[Jill, Jenny],[George]);

if i wanted to loop though and print all to console e.g.

  for(let x=0;x<dogNames.length;x  ){
       console.log(dogNames[x]);
    }

is it possible to hide any value after ',' in each array

so my printed value may be

Bill Ben Jack Barbra Jill George

with Allen and Jenny both hidden/removed

Unsure where to start. tried using .split() but unsure how to use it on 2d arrays.

CodePudding user response:

.split(",") is for strings, you are using arrays. So basically you can convert to string and split or just pick the first element of every row (your second array).

dogNames = [[]];
dogNames.push(["Bill"],["Ben"],["jack", "Allen"],["Barbra"],["Jill", "Jenny"],["George"]);


// SOLUTION 1 --> JUST PICK ARRAY FIRST ELEMENT
for(let x=0;x<dogNames.length; x  ){
  console.log(dogNames[x][0]);
}

//SOLUTION 2 --> ARRAY to STRING
for(let x=0;x<dogNames.length;x  ){
 const dogNameRow = dogNames[x];
 const dogString = dogNameRow.join();
 console.log(dogString.split(",")[0]);
}

CodePudding user response:

You have several syntax mistakes like parens around x which should be square brackets and also you need strings to be in quotes in the arrays.

Also you don't need an array in an array when you first declare dogNames

If you compare your code with my code you will see what I mean.

The main answer to your question is to include the [0] in console.log(dogNames[x][0]); so you just log the first element of the sub arrays

dogNames = [];

dogNames.push(['Bill'],['Ben'],['jack', 'Allen'],['Barbra'],['Jill', 'Jenny'],['George']);
  
for(let x=0;x<dogNames.length;x  ){
  console.log(dogNames[x][0]);
}

  • Related