Finding the index position of a 2-dimensional array

Hello,

I am trying to find the index position of an array element, but whenever I log the index, it shows me a -1.

Here’s my code :slight_smile:

let array = [];
let a = "18647AF0D0,59,6]1864726D1,65,5]1864726A,85,5]1864726A,75,5]";
let boss = a.split(']');
//document.write(boss);
// console.log(b);
for (let i=0;i<boss.length  ;i++) {
  //document.write(boss[i]);
  let final= boss[i].split(',');
  //console.log(final);
  
  array = [...array, [final]];
}
for (let i =0;i<array.length-1;i++) {
  for (let j =0;j<3;j++) {
    console.log(array[i][0][j]);
  }
}


index = array.indexOf('1864726A');
console.log(index);

codepen ;- https://codepen.io/kanxababu/pen/poKdXbW

Hi,

So you have:

let a = "18647AF0D0,59,6]1864726D1,65,5]1864726A,85,5]1864726A,75,5]";
let boss = a.split(']');

which gives you:

[ "18647AF0D0,59,6", "1864726D1,65,5", "1864726A,85,5", "1864726A,75,5", "" ]

From your question, I assume you are trying to find the index of the elements in that array (boss) that contain the string ‘1864726A’. This would be 2 & 3.

Did I get that right?

If so, you can do it like this:

const arr = "18647AF0D0,59,6]1864726D1,65,5]1864726A,85,5]1864726A,75,5]";
const chunks = arr.split(']');

const indexes = chunks.reduce((arr, el, index) => {
  if (el.includes('1864726A')) arr.push(index);
  return arr;
}, []);

console.log(indexes);

If you need to do this with more than one string, it wouldn’t be hard to wrap all of that up into a function.

HTH

This is going harder for me. Thanks. I need your suggestions. The data you see is being sent from a server. It is in string format.

18647AF0D0,59,6]1864726D1,65,5]1864726A,85,5]1864726A,75,5]

So with every string end, I am sending a closed bracket(]), which means the first data is completed.

8647AF0D0,59,6]

8647AF0D0 = mac
59 = ttl
6 = time

As a result, this data must be displayed on a HTML site, which has already been designed.

So the reason I needed to store it in the array is because I am getting a repeated Mac ID with an updated value of ttl and time.

I mean to say TTL and time, which get updated every time, and then the server resends it to me, and then I need to update that value on a web page, but if that mac address already exists, then I will just make sure to put an updated value on that which is (TTL and TIME ).
Data should not re-enter .

Thank You

Thanks for the explanation. I’m afraid though that I’m still not sure what you’re trying to do.

You obviously have this as input:

18647AF0D0,59,6]1864726D1,65,5]1864726A,85,5]1864726A,75,5]

What would you like the output to be?

1 Like

and with every set of data I am adding a close bracket, which means the set of data is now complete.

So The data look like this

mac = "18647AF0D0";
TTL = "59"
TIME = "6"

And the server continues to send the data, which is added to the variable a

Now This data I need to display on the web server on a HTML site, which has already been designed.

So The issue is here when the server sends sometime it sends a same mac value with a updated TTL and TIME

For example, like this

1864726A,85,5]1864726A,75,5]

Here, if you see, I am getting the same mac value, so what I want to do is if the mac value already exists, then just update the TTL and TIME values on the same position; it should not be creating another entry.

So, I was trying to store this value into an array using a split function, but it’s getting too complicated, so I am stuck here.

Here is my html page:- https://codepen.io/kanxababu/pen/KKeZKQZ

My english is bad and my explanation is also bad sorry for that and thank you so much for helping

No worries :slight_smile:

Could you maybe create an array of objects, where each object has three properties: mac, ttl and time.

You could then iterate over your response. If the mac address already exists in the array, you could update the ttl and time values, otherwise you would create a new entry for that mac address.

Something like this:

const res = "18647AF0D0,59,6]1864726D1,65,5]1864726A,85,5]1864726A,75,5]";
const data = [];

res.split(']').forEach((el) => {
  if (!el) return;

  const [mac, ttl, time] = el.split(',');
  const obj = data.find(o => o.mac === mac);

  if (obj) {
    obj.ttl = ttl;
    obj.time = time;
  } else {
    data.push({ mac, ttl, time });
  }
});

console.log(data);

This would give you:

[
  { mac: "18647AF0D0", ttl: "59", time: "6" },
  { mac: "1864726D1", ttl: "65", time: "5" },
  { mac: "1864726A", ttl: "75", time: "5" },
]

which you could use to update the page.

Would that work?

1 Like

So, I’ve realised that I need to learn more. This worked like a charm.

Thanks Now I will figure out sending this array to web page. thank you again If I stuck, I would surely come again.

1 Like

All are working fine. But it’s not updating the TTL,status whenever it revises the same entry.

On the webpage? Or how do you mean?

In an array to … wait let me show you ,

No Sir My bad. I have done changes in your code that’s why it was happening. sorry

Oh ok, cool. So it’s working now?

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
	if (this.readyState == 4 && this.status == 200) {
		var res = this.responseText;
        console.log(res);
        const data = [];
        res.split(']').forEach((el) => {
            if (!el) return;

        const [mac, ttl, time] = el.split(',');
        const obj = data.find(o => o.mac === mac);

        if (obj) {
            obj.ttl = ttl;
            obj.time = time;
        } else {
            data.push({ mac, ttl, time });
        }
    });
    

    console.log(data);
    
    for (var i = 0; i < data.length; i++) {
        let row = myTable.insertRow();
        let cell0 = row.insertCell(0);
        let cell1 = row.insertCell(1);
        let cell2 = row.insertCell(2);
        let cell3 = row.insertCell(3);
        cell0.innerHTML = i;
        cell1.innerHTML = data[i].mac;
        cell2.innerHTML = data[i].ttl;
        cell3.innerHTML = data[i].time;
        

    }
    
    }
    


    


};
xhr.open("GET", "http://********/wifimac", true);
xhr.send();

It works in the web browser, but I need to refresh for new data. Can I add a setinterval function so that the directly updates the data? But if I do that in the web browser, the data starts disaplying duplicate values, which may be due to the loop.

Yeah, that should work. Let me summarize:

  • You want to make an Ajax request every (for example) 5 seconds
  • The result of that request will be like you showed previously — a string in the form of: 18647AF0D0,59,6]1864726D1,65,5]1864726A,85,5]1864726A,75,5]
  • Every time that request runs you want to update the data object as we did above (updating an entry if the mac address already exists, creating it if it doesn’t)
  • Every time the Ajax request runs, you want to reflect any changes to the data object on your page.

Did I get that right?

Yes thanks. will do this later. Now I am analysing your code and trying to understand how you did it. If I wasn’t able to do that, it means that I have less practise and nothing else, is that correct? Should I do more projects or practice? I had been doing this for four days and was literally frustrated because I was just copying and pasting whatever I got. And today, finally, I was able to do it because of you.

Projects are good. Everyone learns differently, but I like to build stuff and then search for the solutions to problems as I run into them.

It also helps to break larger problems down into smaller ones, which then become more manageable.

The code uses some more modern JavaScript syntax, so if there’s anything you don’t understand, please just say.

Otherwise, here’s a breakdown:

// Split the string at every '[' character
// This gives you an array that you can call forEach on
res.split(']').forEach((el) => {

  // As the original string ends in a '[' this means that the last element of res is an empty string
  // This is a guard clause to check for that and to do nothing if an empty string is encountered
  if (!el) return;

  // el is the current element of the ers array
  // We can split it again on ',' to get the values we need
  // Search for array destructuring if this is new for you
  const [mac, ttl, time] = el.split(',');

  // See if there is any object in the array with the current mac address
  // Search 'filter array of objects javascript'
  // Or see: https://www.sitepoint.com/community/t/filter-array-of-object/286730/3
  const obj = data.find(o => o.mac === mac);

  // Did we find an object containing the current mac address
  if (obj) {
    // If so, update its properties
    obj.ttl = ttl;
    obj.time = time;
  } else {
    // Otherwise create a new object and add it to the array
    // This uses object shorthand where the name of the property and the value are the same 
    // meaning only one needs to be specified
    data.push({ mac, ttl, time });
  }
});

console.log(data);

I’m off out for the evening now, but if you have any more questions, I can pick this up tomorrow.

2 Likes

Thanks a Lot.

Hello,

Capture

" Address: bb:ca:43:ee:9c:aa"

is it possible can we make Name,Address,manufacture a index . Now it all this are in a single string

I tried but I am not able to figure it out where to set interval function .

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    
        if (this.readyState == 4 && this.status == 200) {
            var res = this.responseText;

            const data = [];
            res.split(']').forEach((el) => {
                if (!el) return;

            const [mac, ttl, time] = el.split(',');
            const obj = data.find(o => o.mac === mac);

            if (obj) {
                obj.ttl = ttl;
                obj.time = time;
            } else {
                data.push({ mac, ttl, time });
            }
        })

    



    for (var i = 0; i < data.length; i++) {
        let row = myTable.insertRow();
        let cell0 = row.insertCell(0);
        let cell1 = row.insertCell(1);
        let cell2 = row.insertCell(2);
        let cell3 = row.insertCell(3);
        cell0.innerHTML = i;
        cell1.innerHTML = data[i].mac;
        cell2.innerHTML = data[i].ttl;
        cell3.innerHTML = data[i].time;
        

    }
    
    }
    


    


};
xhr.open("GET", "http://192.168.43.154/wifimac", true);
xhr.send();