javascript array multidimension search index - javascript

I have an array in javascript. I've been trying to search the index but it is very frustrating. There is an object inside an array, and inside the object have an array as a value.
This is what the source code looks like:
rows = [{"id":"id0","cell":["array1","array2"]},{"id":"id1","cell":["array3","array4"]}];
I've tried this:
var v = {cell:["array1","array2"]};
rows.indexOf(v)
And also have a radio button:
<input type="radio" name='array' value="array1, array2">
jQuery here:
var i = $("input:checked").val().split(',');
rows.indexOf(i)
which has an index result of -1

Try this. It's a functional approach that loops through each index in rows, and returns true if there's a match.
var rows = [{"id":"id0","cell":["array1","array2"]},{"id":"id1","cell":["array3","array4"]}];
var index = rows.findIndex(function(i) {
return JSON.stringify(i.cell) == JSON.stringify(["array1","array2"])
});
console.log(index);
The output should return 0. The reason we need to convert both objects into JSON.strings is because of how javascripts handles the equality of two objects. You can read more about it here.

Related

Remove duplicate comma seperated numbers from input text value in jQuery

I have an input on a webpage with a value like this 1,7,1,4,22,58,58,1,1,4,7
<input type="text" name="hello" id="thankyouforhelping" value="" aria-invalid="false">
I tried numerous ways to remove the duplicate from it but none of the ways work.
I tried: jQuery function to get all unique elements from an array? and jQuery function to get all unique elements from an array?
I get the value like this:
/* Grabbing up to date value to remove duplicates */
$upToDateValue = $('.wdrow-'+$projectrow+' .tasks-created input').val();
The value will always be numbers that are comma seperated but how can I remove all the duplicated numbers. And if you are willing how could I also sort it from low to high?
So that the end result would be 1,4,7,22,58
/* Removing duplicates */
$newValue = ???;
PS: I see a lot of answers on previously asked questions are javascript but I have my code in jQuery and I am struggling a lot with adapting those answers to my jQuery code. So I am sorry that this question is so closely related to others already available. Questions like this: Get all unique values in a JavaScript array (remove duplicates)
I have no clue how to adapt the accepted answer to my code.
Thanks everyone for helping!
##Heretic_Monkey helped me out a lot and this is the result:
$upToDateValue = $('.wdrow-'+$projectrow+' .tasks-created input').val();
/* Removing duplicates */
var values = $upToDateValue.split(','); values = [...new Set(values)]; values.sort(); $newValue = values.join(',');
/* Setting new value to input */
$('.wdrow-'+$projectrow+' .tasks-created input').val($newValue);
Combining answers from How to convert a comma separated string to an array?, Easy way to turn JavaScript array into comma-separated list?, and Get all unique values in a JavaScript array (remove duplicates), this is one way of performing the task:
// Get the value
var $upToDateValue = $('.wdrow-'+$projectrow+' .tasks-created input').val();
// Split into an array
var values = $upToDateValue.split(',');
// Remove the duplicates and make a new array
values = [...new Set(values)];
// Sort the new array
values.sort();
// Create a new comma-delimited string from the array
var $newValue = values.join(',');
// Set the new value to input
$('.wdrow-'+$projectrow+' .tasks-created input').val($newValue);
References for code used:
split
Set
... aka "spread syntax"
sort
join
I updated the code, you can copy the function and paste in your code.
then call it in your code using $newValue = unique(values)
Try this code:
function unique (value) {
const valueList = value.split(",")
const unique = valueList.filter((item, index, valueList) => {
return index === valueList.indexOf(item);
});
const sorted = unique.sort(function(a, b) { return a - b; });
return sorted.join(',')
}
/* you can use it this way */
const value = "1,7,1,4,22,58,58,1,1,4,7"
$newValue = unique(value)
/* printing */
console.log($newValue)

Two Dimensional Array - arr[i][0] Gives Wrong Result - JavaScript ASP.NET C#

I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0

Getting last item in array using javascript

I'm trying to get the last item in a array using JavaScript.
But I'm always getting all items in the array.
So far, I've tried several methods. Here is my code:
var pathCoords = ['1','2','3','4','5'];
var sample1 = pathCoords[pathCoords.length -1];
var sample2 = pathCoords.slice(-1)[0];
console.log(sample1, sample2);
Maybe You can use splice method of array like this :
var sample = pathCoords.splice(pathCoords.length-1);

What is a faster way to write this function to delete rows/objects in a table?

So, I have this function that, after an update, deletes elements from a table. The function, lets call it foo(), takes in one parameter.
foo(obj);
This object obj, has a subfield within called messages of type Array. So, it would appear something like this:
obj.messages = [...];
Additionally, inside of obj.messages, each element contains an object that has another subfield called id. So, this looks something like:
obj.messages = [{to:"You",from:"Me",id:"QWERTY12345.v1"}, ...];
Now, in addition to the parameter, I have a live table that is also being referenced by the function foo. It uses a dataTable element that I called oTable. I then grab the rows of oTable and copy them into an Array called theCurrentTable.
var theCurrentTable = oTable.$('tr').slice(0);
Now, where it gets tricky, is when I look into the Array theCurrentTable, I returned values appear like this.
theCurrentTable = ["tr#messagesTable-item-QWERTY12345_v1", ...];
The loop below shows how I tried to show the problem. While it works (seemingly), the function itself can have over 1000 messages, and this is an extremely costly function. All it is doing is checking to see if the current displayed table has the elements given in the parameter, and if not a particular element, delete it. How can I better write this function?
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
for(var idx = 0; idx < theCurrentTable.length; idx++){ // through display
var displayID = theCurrentTable[idx].id.replace('messagesTable-item-','').replace('_','.');
var deletionPending = true;
for(var x = 0; x < theReceivedMessages.length; x++){
var messageID = theReceivedMessages[x].id;
if(diplayID == messageID){
console.log(displayID+' is safe...');
deletionPending = false;
}
}
if(deletionPending){
oTable.fnDeleteRow(idx);
}
}
I think I understand your problem. Your <tr> elements have an id that should match an item id within your messages.
First you should extract the message id values you need from the obj parameter
var ids = obj.messages.map(function (m) { return '#messagesTable-item-' + m.id; });
This will give you all the rows ids you need to keep and then join the array together to use jQuery to select the rows you don't want and remove them.
$('tr').not(ids.join(',')).remove();
Note: The Array.prototype.map() function is only supported from IE9 so you may need to use jQuery.map().
You could create a Set of the message ID values you have, so you can later detect if a given ID is in this Set in constant time.
Here is how that would look:
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
// Pre-processing: create a set of message id values:
var ids = new Set(theReceivedMessages.map( msg => msg.id ));
theCurrentTable.forEach(function (row, idx) { // through display
var displayID = row.id.replace('messagesTable-item-','').replace('_','.');
// Now you can skip the inner loop and just test whether the Set has the ID:
if(!ids.has(displayId)) {
oTable.fnDeleteRow(idx);
}
});
So now the time complexity is not any more O(n.m) -- where n is number of messages, and m the number of table rows -- but O(n+m), which for large values of n and m can make quite a difference.
Notes:
If theCurrentTable is not a true Array, then you might need to use a for loop like you did, or else use Array.from(theCurrentTable, function ...)
Secondly, the implementation of oTable.fnDeleteRow might be that you need to delete the last rows first, so that idx still points to the original row number. In that case you should reverse the loop, starting from the end.

JavaScript find index of value in a column of an array (read from csv with papaparse)

Very close but slightly more complex than this question I have an array and I want to obtain the index of the array of the first occurrence of a value of a given object of this array.
My array has several objects of integer and text, and has an id object of integers (which I call with this instruction wup[i].id).
[edit] The array comes from reading a csv file with header with papaparse.
wup = ["id", "cityName", etc ... ]
[20002, "Tokyo", etc ... ]
[20003, "GoiĆ¢nia", etc ... ]
It is in this id object only that I want to find the input value and finally get the index of this input value. This is certainly using indexOf but how to focus the search only in the id object?
[edit] the instruction that fails is the following (try to find the occurrence of tn[iter].idOri in the array wup, that I expect to retrieve in the variable iOri):
var iOri = wup.indexOf(tn[iter].idOri);
Hoping it is clear enough.
There are lots of ways to do this, map your array down to a flat array of ids:
var myId = 3;
var ids = array.map(function(obj) {
return obj.id;
});
var index = ids.indexOf(myId);
A more succinct (and better - because it only requires one iteration) method would be to use Array.findIndex:
var myId = 3;
var index = array.findIndex(function(obj) {
return obj.id === myId;
});
With es6:
var myId = 3;
var index = array.map(obj => obj.id).indexOf(myId);
or
var myId = 3;
var index = array.findIndex(obj => obj.id === myId);

Categories