-2

I have a Multidimensional array as shown below:

[
["1","success","5"],
["2","success","5"],
["3","success","5"],
["4","fail","5"],
["5","fail;","5"],
["6","fail","5"],
["7","success","5"],
["8","fail","5"],
];

what I need is to select particular rows based on the success and fail type. which means for eaxmple i have to only get the data whose second column is named success

I have written a code but it gives me values in separate arrays. I want the data in this format

 [
    ["1","success","5"],
    ["2","success","5"],
    ["3","success","5"],
    ["7","success","5"],
]

The code that I have tried is the folllowing:

  var success = [];
     for(var i=0;i<arr.length;i++)
     {
        if(arr[i][1] =='success')
        {
         success = [arr[i]];
         console.log(success);
        }
     }

I want all the data in single array. Here is the Fiddle Link that I Tried: https://jsfiddle.net/abnitchauhan/09zchjak/

Bunty Sharma
  • 104
  • 12
  • 1
    The problem with your code is that you're *replacing* the value in `success` on every match. Instead, you want to *add to* it: `success.push(arr[i])`. (But as the answer below says, `filter` is for this specific purpose.) – T.J. Crowder Dec 14 '20 at 09:42
  • I think I can help you to solve your problem sir, how to discuss sir? – ProLuck Dec 14 '20 at 09:59

1 Answers1

2

You could use array filter method.

const data = [
  ['1', 'success', '5'],
  ['2', 'success', '5'],
  ['3', 'success', '5'],
  ['4', 'fail', '5'],
  ['5', 'fail;', '5'],
  ['6', 'fail', '5'],
  ['7', 'success', '5'],
  ['8', 'fail', '5'],
];
const success = data.filter((x) => x[1] === 'success');
console.log(success);
mr hr
  • 3,162
  • 2
  • 9
  • 19