0

This is my html structure. Here, i have created two attributes for each element. How to push attribute value into an array (like this structure, [[1,0],[1,1],[1,2],[0,2],[2,2],[1,3],[1,4]])?

<div id="demo">
     <div data-floor="1" data-floor-sub="0">Div1</div>
     <div data-floor="2" data-floor-sub="0">Div2</div>
     <div data-floor="3" data-floor-sub="0">Div3</div>
     <div data-floor="3" data-floor-sub="1">Div4</div>
     <div data-floor="3" data-floor-sub="2">Div5</div>
     <div data-floor="4" data-floor-sub="0">Div6</div>
     <div data-floor="5" data-floor-sub="0">Div7</div>
</div> 

1 Answer 1

3

Use map()

var multiDimArray = $('#demo div').map(function() {
  var innerArray = [];
  innerArray.push([$(this).data('floor'), $(this).data('floor-sub')]);
  return innerArray;
}).get();

console.log(multiDimArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="demo">
  <div data-floor="1" data-floor-sub="0">Div1</div>
  <div data-floor="2" data-floor-sub="0">Div2</div>
  <div data-floor="3" data-floor-sub="0">Div3</div>
  <div data-floor="3" data-floor-sub="1">Div4</div>
  <div data-floor="3" data-floor-sub="2">Div5</div>
  <div data-floor="4" data-floor-sub="0">Div6</div>
  <div data-floor="5" data-floor-sub="0">Div7</div>
</div>

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

4 Comments

How to store value, like this structure [1,0], [2,0], [3,0], [3,1], [3,2], [4,0], [5,0].... @AmmarCSE
@Sathya, my answer gives an array of arrays, isnt that what you wanted?
your answer is showing like [1, 0, 2, 0, 3, 0, 3, 1, 3, 2, 4, 0, 5, 0]. But i want to store like this, [1,0], [2,0], [3,0], [3,1], [3,2], [4,0], [5,0]. Is there anyway to get result like that way?
Thanks... @RickHitchcock

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.