Deleting from an array based on a string value - javascript

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');

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)
}
})
})
})

filter a array from values stored in array

I have an array
sourceArray = [{'type':'A'}, {'type':'B'}, {'type':'C'}, {'type':'D'}];
arrayB = ['B', 'C'];
I want to filter array sourceArray from values which arrayB contains.
We can do this by iterating arrayB, but just want some good way to do this.
filteredArray = [];
for(x in arrayB)
{
filteredArray.concat( sourceArray.filter(function(e1){ return e1.type == arrayB[x])} );
}
can be have any way to do this more gracefully.
Just .filter it:
sourceArray = [{'type':'A'}, {'type':'B'}, {'type':'C'}, {'type':'D'}];
arrayB = ['B', 'C'];
result = sourceArray.filter(function(item) {
return arrayB.indexOf(item.type) >= 0;
});
document.write("<pre>" + JSON.stringify(result,0,3));
[].filter(func) iterates an array and collects elements for which func returns true. In our function, we check whether arrayB contains item.type and return true if it does (see indexOf).
ES6 solution, for those who already use it:
sourceArray = [{'type':'A'}, {'type':'B'}, {'type':'C'}, {'type':'D'}];
arrayB = ['B', 'C'];
setB = new Set(arrayB)
result = sourceArray.filter(item => setB.has(item.type))
There's the solution of filtering and using indexOf, but it contains a hidden iteration which is costly if your arrayB array contains more than just a few elements.
In the general case, the efficient solution is to build a hash map of the elements so that the filtering operation is faster. This can be done like this:
var filteredArray = sourceArray.filter(
function(v){ return this[v.type] }.bind(arrayB.reduce(
function(s,v){ s[v]=1; return s }, Object.create(null)
))
)
In this code arrayB.reduce(function(s,v){ s[v]=1; return s }, {})) is an object whose keys are the valid types : {B: 1, C: 1}. JavaScript engines are very fast at repetitively retrieving the properties of such an object.
var sourceArray = [{
'type': 'A'
}, {
'type': 'B'
}, {
'type': 'C'
}, {
'type': 'D'
}];
var arrayB = ['B', 'C'];
var desiredArr = sourceArray.filter(function (val) {
for (var i = 0; i <= arrayB.length; ++i) {
if (val.type == arrayB[i]){
return val;
}
}
});
alert(JSON.stringify(desiredArr));

Using Underscore.js's invoke with lastIndexOf

// Why doesn't this:
_.invoke(['D','C'], 'lastIndexOf', ['A','B','C'])
// Return this:
[-1,2]?
I've got a string. (Input)
'ABC'
Split into an array. (InputBuffer)
['A','B','C']
I've also got an array with arbitrary characters. (TriggerChars)
['D','E']
I want to check the last item in the InputBuffer to see if matched any of the TriggerChars.
I want to get the last occurrence of both TriggerChars in the InputBuffer.
_.invoke(['D','E'], 'lastIndexOf', ['A','B','C']);
// Returns [-1,-1] since C isn't D or E.
_.invoke(['D','C'], 'lastIndexOf', ['A','B','C']);
// Why doesn't this return [-1,2]
_.lastIndexOf(['A','B','C'],'D') == -1
_.lastIndexOf(['A','B','C'],'C') == 2
What am I not getting with Invoke?
http://underscorejs.org/#invoke
var InputBuffer = ["A","B","C"];
var TriggerChars = ["D","E"];
_.indexOf( TriggerChars, InputBuffer[InputBuffer.length-1] ) > -1;
Evaluates to true if this: I want to check the last item in the InputBuffer to see if matched any of the TriggerChars.
What you need is:
_.map(['D', 'C'], function (x) { return _.lastIndexOf(['A', 'B', 'C'], x)})
var inputBuffer = ["A","B","C"];
var triggerChars = ["D","E"];
triggerChars.indexOf(inputBuffer[inputBuffer.length-1]) > -1
or just skip underscore, the exact same solution above except the dependency,
ok I updated it alittle
var inputBuffer = ["A","B","C"];
var triggerChars = ["D","C"];
var index = [];
for(var i = 0; i < triggerChars.length; i++){
index.push(inputBuffer.lastIndexOf(triggerChars[i]));
}
console.log(index);
-> [-1,2]

Function to convert an Array to an Associative array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert flat array [k1,v1,k2,v2] to object {k1:v1,k2:v2} in JavaScript?
I want to convert an array to an associative array in JavaScript.
For example, given the following input,
var a = ['a', 'b', 'c', 'd'];
I want to get the next associative array as output:
{'a' : 'b', 'c' : 'd'}
How can I do that?
Using .forEach:
var a = ['a', 'b', 'c', 'd'];
var obj_a = {};
a.forEach(function(val, i) {
if (i % 2 === 1) return; // Skip all even elements (= odd indexes)
obj_a[val] = a[i + 1]; // Assign the next element as a value of the object,
// using the current value as key
});
// Test output:
JSON.stringify(obj_a); // {"a":"b","c":"d"}
Try the following:
var obj = {};
for (var i = 0, length = a.length; i < length; i += 2) {
obj[a[i]] = a[i+1];
}
There is no such thing as an associative array, they're called Objects but do pretty much the same :-)
Here's how you would do the conversion
var obj = {}; // "associative array" or Object
var a = ['a', 'b', 'c', 'd'];
for(index in a) {
if (index % 2 == 0) {
var key = a[index];
var val = a[index+1];
obj[key] = val;
}
}

How can i delete something out of an array?

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.

Categories