-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/

2
  • 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.) Commented Dec 14, 2020 at 9:42
  • I think I can help you to solve your problem sir, how to discuss sir? Commented Dec 14, 2020 at 9:59

1 Answer 1

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);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.