0

I want to create new Array from old array where each elements length is greater than its previous element. I have a old array like below:

Arr=[[2,3],[1,2],[2,4,5],[6,6,3],[3,2,1],[4,2,3],[4,2,1,2],[2,1,4,5]]

Now I have to create a new array like below from above array:

newArr = [[2,3],[2,4,5],[4,2,1,2]]

Using Javascript.

3 Answers 3

2

We loop over all array and if current length less then next, we push element in result and change a current length

const findArray = () => {
  let currentLength = 0
  const result = []
  for (let i = 0; i < arr.length; i += 1) {
    if (arr[i].length > currentLength) {
      result.push(arr[i])
      currentLength = arr[i].length
    }
  }
  return result
}
Sign up to request clarification or add additional context in comments.

Comments

1

I wood here to demonstrate this code with real value (the output is printed in screen)

<!DOCTYPE html>
<html>
<body>

<p>Click the button to create an array, then display its length.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
   
  var Arr=[[2,3],[1,2],[2,4,5],[6,6,3],[3,2,1],[4,2,3],[4,2,1,2],[2,1,4,5]];
  
var text = ""; 
var len=0;
var i;
for (i = 0; i < Arr.length; i++) { 
 if (len < Arr[i].length )
  {text += Arr[i] + "<br>"; len=Arr[i].length;}
}
  
  document.getElementById("demo").innerHTML = text;


}
</script>

</body>
</html>

Result is:

2,3
2,4,5
4,2,1,2

Comments

1

You could take a closure over the next wanted length and filter the array by checking the index or actual length. If one of the both conditions is true, set l to the next expected length.

const
    array = [[2, 3], [1, 2], [2, 4, 5], [6, 6, 3], [3, 2, 1], [4, 2, 3], [4, 2, 1, 2], [2, 1, 4, 5]],
    result = array.filter(
        (l => ({ length }) => (!l || l === length) && (l = length + 1))
        (0)
    );

console.log(result);

Comments

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.