How can i delete something out of an array? - javascript

My problem is that i have to delete something out of an array. I found out how to delete something out of a listbox. But the problem is that the listbox is filled by an array. So if I don't delete the value (I deleted out of the listbox) out of the array. The value keeps coming back when you add a new item. BTW: I am new to php and javascript.
My code is:
function removeItem(veldnaam){
var geselecteerd = document.getElementById("lst"+veldnaam).selectedIndex;
var nieuweArray;
alert(geselecteerd);
alert(document.getElementById(veldnaam+'hidden').value);
For (var i = 0, i<= arr.lenght, i++) {
If (i= geselecteerd){
nieuweArray = arr.splice(i,1);
document.getElementById(veldnaam+'hidden').value = arr;
}}
document.getElementById("lst"+veldnaam).remove(geselecteerd);
}

Use the delete operator. I'm assuming you are using objects as associative arrays.
var arr = {
"hello": "world",
"foo": "bar"
}
delete arr["foo"]; // Removes item with key "foo"

You can delete elements in an array using the delete command. But it will just set the value to undefined.
var arr = ['h', 'e', 'l', 'l', 'o'];
delete arr[2];
arr => ['h', 'e', undefined, 'l', 'o'];
So it will not remove the item, and make a shorter array, the array will still have 5 elements (0 to 4), but the value has been deleted.
In the case of "associative" arrays, or objects: The property will get erased and it will no longer exist.
var obj = { 'first':'h', 'second':'e', 'third':'l'};
delete obj['first'];
obj => { 'second':'e', 'third':'l'};

Add the following code somewhere
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
and call it like this:
// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);
Article containing the code above and explanation: http://ejohn.org/blog/javascript-array-remove/

var geselecteerd = document.getElementById("lst"+veldnaam).selectedIndex;
var nieuweArray;
var teller = 0;
var oudeArray=document.getElementById(veldnaam+'hidden').value;
var tmpArr="";
nieuweArray=oudeArray.split(":");
for (i = 0; i<nieuweArray.length; i++){
if (!(i==geselecteerd)){
tmpArr = tmpArr+nieuweArray[i]+":";}
teller++;
}
tmpArr = tmpArr + ":";
tmpArr = tmpArr.replace("::","");
document.getElementById(veldnaam+'hidden').value = tmpArr;
document.getElementById("lst"+veldnaam).remove(geselecteerd);
}
This is my solution and it worked. Thanks for your help.

Related

How to loop through multiple arrays, within an array of arrays using a single value for an index?

I'm trying to solve a problem where you have an array
array = [[a,b,c],[e,f,g],[h,i,j]]
I want to loop through the first letter of the first array, then look at the first of all the other arrays then do a comparison whether they're equal or not. I'm unsure how to do this given that a loop will go through everything in its array. I wrote a nested loop below, but I know it's know it's not the right approach. I basically want something that looks
like
if (array[0][0] == array[1][0] == array[2][0]), then repeat for each element in array[0]
var firstWord = array[0];
var remainderWords = array.slice(1);
for(var i = 0; i < firstWord.length; i++){
for (var j = 0; i< remainderWords.length; j++){
if firstWord[i] == remaindersWord[j][i]
}
Any help would be appreciated.
Use Array.every() to check that a condition is true for all elements of an array.
firstWord.forEach((letter, i) => {
if (remainderWords.every(word => word[i] == letter)) {
// do something
}
});
You can use three nested for or .forEach loops to get to the items in the remainderItems array. Try this
var array = [['a', 'b', 'c'], ['b', 'f', 'g'], ['h', 'c', 'j']];
var firstWord = array[0];
var remainderWords = array.slice(1);
firstWord.forEach((l, idx) => {
remainderWords.forEach(arr => {
arr.forEach(v => {
if (l == v) {
// matched do whatever you want with the variable here
console.log(v)
}
})
})
})

Algorithm to sort an array in JS

I have an array
var arr= [
["PROPRI","PORVEC"],
["AJATRN","PROPRI"],
["BASMON","CALVI"],
["GHICIA","FOLELI"],
["FOLELI","BASMON"],
["PORVEC","GHICIA"]
] ;
And I'm trying to sort the array by making the second element equal to the first element of the next, like below:
arr = [
["AJATRN","PROPRI"],
["PROPRI","PORVEC"],
["PORVEC","GHICIA"],
["GHICIA","FOLELI"],
["FOLELI","BASMON"],
["BASMON","CALVI"]
]
The context is : these are somes sites with coordinates, I want to identify the order passed,
For exemple, I have [A,B] [C,D] [B,C] then I know the path is A B C D
I finally have one solution
var rs =[];
rs[0]=arr[0];
var hasAdded=false;
for (var i = 1; i < arr.length; i++) {
hasAdded=false;
console.log("i",i);
for (var j = 0, len=rs.length; j < len; j++) {
console.log("j",j);
console.log("len",len);
if(arr[i][1]===rs[j][0]){
rs.splice(j,0,arr[i]);
hasAdded=true;
console.log("hasAdded",hasAdded);
}
if(arr[i][0]===rs[j][1]){
rs.splice(j+1,0,arr[i]);
hasAdded=true;
console.log("hasAdded",hasAdded);
}
}
if(hasAdded===false) {
arr.push(arr[i]);
console.log("ARR length",arr.length);
}
}
But it's not perfect, when it's a circle like [A,B] [B,C] [C,D] [D,A]
I can't get the except answer
So I really hope this is what you like to achieve so have a look at this simple js code:
var vector = [
["PROPRI,PORVEC"],
["AJATRN,PROPRI"],
["BASMON,CALVI"],
["GHICIA,FOLELI"],
["FOLELI,BASMON"],
["PORVEC,GHICIA"]
]
function sort(vector) {
var result = []
for (var i = 1; i < vector.length; i++) result.push(vector[i])
result.push(vector[0])
return (result)
}
var res = sort(vector)
console.log(res)
Note: Of course this result could be easily achieved using map but because of your question I'm quite sure this will just confuse you. So have a look at the code done with a for loop :)
You can create an object lookup based on the first value of your array. Using this lookup, you can get the first key and then start adding value to your result. Once you add a value in the array, remove the value corresponding to that key, if the key has no element in its array delete its key. Continue this process as long as you have keys in your object lookup.
var vector = [["PROPRI", "PORVEC"],["AJATRN", "PROPRI"],["BASMON", "CALVI"],["GHICIA", "FOLELI"],["FOLELI", "BASMON"],["PORVEC", "GHICIA"]],
lookup = vector.reduce((r,a) => {
r[a[0]] = r[a[0]] || [];
r[a[0]].push(a);
return r;
}, {});
var current = Object.keys(lookup).sort()[0];
var sorted = [];
while(Object.keys(lookup).length > 0) {
if(lookup[current] && lookup[current].length) {
var first = lookup[current].shift();
sorted.push(first);
current = first[1];
} else {
delete lookup[current];
current = Object.keys(lookup).sort()[0];
}
}
console.log(sorted);

What does a[arr1[i]]=true do?

I am a JavaScript beginner. I have previously worked in other programming languages (C, C++ etc). What is the statement a[arr1[i]]=true; doing?
function diff(arr1, arr2) {
var newArr = [];
// Same, same; but different.
var a=[];
for(var i=0;i<arr1.length;i++)
a[arr1[i]]=true;
for(var j=0;j<arr2.length;j++)
if(a[arr2[j]])
delete a[arr2[j]];
else
a[arr2[j]]=true;
for(var k in a)
newArr.push(k);
return newArr;
}
It seems that a is a list of booleans, so that particular assignment sets one of a's indices to true. That index is computed by dereferencing arr1.
In a comment above you expressed a worry to the effect that an array is used as an index inside another array. But no need to worry about that, because it's not the array itself (viz. arr1) that's used as an index, but an element of that array (viz. arr1[i], for some i).
You're wondering about the syntax a[arr1[i]]. It's simple:
arr1[i] value is an index for array a.
If arr1[i] value is a number, 5 as an example. So it will be: a[5]=true. Nothing's special in this case.
As you said in the comment, arr1[i] might be a string, "boy" for example. Then, it will be: a["boy"]=true.
You should know that array index in JavaScript could be a string. But be careful, as W3School said, if you use a named index, JavaScript will redefine the array to a standard object. After that, all array methods and properties will produce incorrect results. For example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined
For more detail, take a look at the warning part in W3School about this.
Here's your code with comments explaining what's going on and sample output
var arr1 = [1,2,'foo','bar'];
var arr2 = [2,3,'foo'];
var diff = diff(arr1, arr2);
console.log( diff ); // ["1", "3", "bar"]
function diff(arr1, arr2) {
var newArr = [];
var a=[];
// Loop through arr1
// set the value of each entry as an index in array `a`
// set the value of the entry in `a` to true
for(var i=0;i<arr1.length;i++)
a[arr1[i]]=true;
// console.log(a); // [1: true, 2: true, foo: true, bar: true]
// Loop through arr2
// check if each entry exists as an index in array `a`
// if it does, delete the value from array `a`
// if not, set the value of the entry in `a` to true
for(var j=0;j<arr2.length;j++)
if(a[arr2[j]])
delete a[arr2[j]];
else
a[arr2[j]]=true;
// console.log(a); // [1: true, 3: true, bar: true]
// put all of the indexs of array `a` to values in `newArr`
for(var k in a)
newArr.push(k);
return newArr;
}
http://jsfiddle.net/daCrosby/6rcf1j72/
From a code-cleanup side, If you want a shorter function you could use something like one of these:
console.log( "Looping", diffLoop ); // [1, "bar", 3]
console.log( "Filtering", diffFilter ); // [1, "bar", 3]
function diffLoop(arr1, arr2){
var arr = arr1;
for(var j=0; j<arr2.length; j++)
if( arr.indexOf( arr2[j] ) > -1 )
arr.splice(arr.indexOf( arr2[j] ), 1);
else
arr.push(arr2[j]);
return arr;
}
function diffFilter(arr1, arr2){
var arr = arr1.concat(arr2);
return arr.filter(function(i) {
var in1 = arr1.indexOf(i) < 0;
var in2 = arr2.indexOf(i) < 0;
return (in1 || in2) && !(in1 && in2);
});
}
http://jsfiddle.net/daCrosby/6rcf1j72/1/
Same logic as in high level languages applies here as well.
This can easily be clarified splitting this to small blocks.
a[arr1[i]]=true;
arr1 - An array of integer
a - An array of boolean

Split nested array into multiple arrays

I have a string that looks like this:
str = {1|2|3|4|5}{a|b|c|d|e}
I want to split it into multiple arrays. One containing all the first elements in each {}, one containing the second element, etc. Like this:
arr_0 = [1,a]
arr_1 = [2,b]
arr_2 = [3,c]
.....
The best I can come up with is:
var str_array = str.split(/}{/);
for(var i = 0; i < str_array.length; i++){
var str_row = str_array[i];
var str_row_array = str_row.split('|');
arr_0.push(str_row_array[0]);
arr_1.push(str_row_array[1]);
arr_2.push(str_row_array[2]);
arr_3.push(str_row_array[3]);
arr_4.push(str_row_array[4]);
}
Is there a better way to accomplish this?
Try the following:
var zip = function(xs, ys) {
var out = []
for (var i = 0; i < xs.length; i++) {
out[i] = [xs[i], ys[i]]
}
return out
}
var res = str
.split(/\{|\}/) // ['', '1|2|3|4|5', '', 'a|b|c|d|e', '']
.filter(Boolean) // ['1|2|3|4|5', 'a|b|c|d|e']
.map(function(x){return x.split('|')}) // [['1','2','3','4','5'], ['a','b','c','d','e']]
.reduce(zip)
/*^
[['1','a'],
['2','b'],
['3','c'],
['4','d'],
['5','e']]
*/
Solution
var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) {
return a.match(/[^|]+/g);
}),
i,
result = {};
for (i = 0; i < str[0].length; i += 1) {
result["arr_" + i] = [+str[0][i], str[1][i]];
}
How it works
The first part, takes the string, and splits it into the two halves. The map will return an array after splitting them after the |. So str is left equal to:
[
[1,2,3,4,5],
['a', 'b', 'c', 'd', 'e']
]
The for loop will iterate over the [1,2,3,4,5] array and make the array with the appropriate values. The array's are stored in a object. The object we are using is called result. If you don't wish for it to be kept in result, read Other
Other
Because you can't make variable names from another variable, feel free to change result to window or maybe even this (I don't know if that'll work) You can also make this an array
Alternate
var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) { return a.match(/[^|]+/g); }),
result = [];
for (var i = 0; i < str[0].length; i += 1) {
result[i] = [+str[0][i], str[1][i]];
}
This is very similar except will generate an Array containing arrays like the other answers,

Deleting from an array based on a string value

I have defined an array like so :
var myArray = {myNewArray: ['string1' , 'string2' , 'string3']};
I want to iterate over the array and delete an element that matches a particular string value. Is there a clean way in jQuery/javascript to achieve this ?
Or do I need to iterate over each element, check its value and if its value matches the string im comparing, get its id and then use that id to delete from the array ?
Here's a JSFiddle showing your solution
var strings = ['a', 'b', 'c', 'd'];
document.write('initial data: ' + strings);
var index = 0;
var badData = 'c';
for(index = 0; index < strings.length; index++)
{
if(strings[index] == badData)
{
strings.splice(index, 1);
}
}
document.write('<br>final data: '+ strings);​
JavaScript arrays have an indexOf method that can be used to find an element, then splice can be used to remove it. For example:
var myNewArray = ['A', 'B', 'C'];
var toBeRemoved = 'B';
var indexOfItemToRemove = myNewArray.indexOf(toBeRemoved);
if (indexOfItemToRemove >= 0) {
myNewArray.splice(indexOfItemToRemove, 1);
}
After that code executes, myNewArray is ['A', 'C'].
You can use Array.filter.
filteredArray = myArray.myNewArray.filter(function(el){
return el === "string";
});
You can check compatibility at Kangax's compat tables.
You could filter the array using $.grep
var myArray = {myNewArray: ['string1' , 'string2' , 'string3']};
myArray = { myNewArray: $.grep(myArray.myNewArray,function(val){
return val !== "string1";
})};
//console.log(myArray);
my newARR = oldArr.splice( $.inArray( removeItem , oldArr ) , 'deleteThisString');

Categories