0

Let's say I have this nested arrays structure:

    [
    ["qltdm", Array(1)]
    ["qltdm", Array(0)]
    ["qlctf", Array(0)]
    ["qlctf", Array(1)]
    ]

I need to filter them in a way that first values cannot be duplicates, and that precedence have the second value (array) which is greater then 0.

So, in short to be left with this:

    [ 
    ["qltdm", Array(1)]
    ["qlctf", Array(1)] 
    ]

Help is appreciated.

1
  • Have you tried anything so far? Commented Oct 21, 2018 at 11:03

1 Answer 1

3
const arr =  [
  ["qltdm", Array(1)],
  ["qltdm", Array(0)],
  ["qlctf", Array(0)],
  ["qlctf", Array(1)]
];


const newArr = [...new Set(arr.filter(o => o[1].length))]

Here it will filter only values where nested array length is bigger 0, and will add it in Set, Set only can contain unique values, so duplicate values will not be added here, after that Set values will be spreaded in new array by ... operator

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

4 Comments

@NirTzezana there is babeljs.io, which can be used for those browsers, why using old ES5, if there is ES6+?
Of course babel is an option, I just noted a fact (if OP is going to test this on IE11 and downwards).
Very nice, I considered using Set in some capacity, but this solution eluded me. Performance wise this is ok, right ? Using set only to get unique values and then spread it in new array ?
yes with performance it should be ok, Set is used for getting unique values, also Set is working faster than arrays, because Set doesn't use loops, you can also do not spread Set in new array if you want to use it as Set and increase your performance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.