change checkbox values using a javascript array - javascript

I have an javascript array filled with values of checkboxes in a html file. How can i find the specific element and change checksign from jquery.
jQuery.each(substr, function() {
var n = this;
$('input[type=checkbox]').each(function () {
$('input[name='+n+']').attr('checked', true);
});
});
Substr is the array filled with names.
substr = {'a', 'b', 'c', 'd'}
.The above code does not work. please help

I think substr = {'a', 'b', 'c', 'd'} should be substr = ['a', 'b', 'c', 'd'].
jQuery.each(substr, function(i, val) {
// val = a, b, c... etc
$('input[type=checkbox][name="'+ val +'"]').attr('checked', true);
});

Related

Removing/pop elements from array

I know this could be quite simple for someone else but I can't think of any solution.
I have an array called breadcrumb with the following elements
breadcrumb = [a, b, c, d]
I also know the index of b. How do I pop all other elements from the array after index of b in JavaScript. the final array should look like this
breadcrumb = [a, b]
There's the slice method in the Array prototype :
var breadcrumb = ['a', 'b', 'c', 'd'];
// in case you have to find the index of the element
var index = breadcrumb.indexOf('b');
breadcrumb = breadcrumb.slice(0, index + 1) // now breadcrumb = ['a', 'b'];
Im pretty sure the accepted answer from this SO question is exactly what you are looking for:
var array = ['one', 'two', 'three', 'four'];
array.length = 2;
alert(array);
You should use array.splice to remove from next element
Syntax: array.splice(index, deleteCount)
var data= ['a', 'b', 'c', 'd'];
data.splice(1+1);
console.log(data)
There are various ways of achieving this.
As you said you know the index of the position from where you need to pop all the elements
1.
var position=2
var breadcrumb = [a, b, c, d];
var length=breadcrumb.length;
var loop;
for(loop=position;loop<length;loop++)
breadcrumb.pop();
2. You can use slice to do this.
var position=2;
var breadcrumb = ["a", 'b', 'c', 'd'];
var length=breadcrumb.length;
var result_arr=breadcrumb.slice(0,position);
3.You can also use splice to do this
var position=2;
var breadcrumb = ["a", 'b', 'c', 'd'];
var length=breadcrumb.length;
var result_arr=breadcrumb.splice(0,position);

Push and remove duplicates of array

I have an array (or Set?) of arr = ['a', 'b', 'c'] and I want to add d to it, which could be done with arr.push('d').
But I only want unique values in the array, and I want the latest values added to be in the front of the array.
So if I first add d the array should become ['d', 'a', 'b', 'c'] and if I now add b the array should become ['b', 'd', 'a', 'c'] etc.
Should it be something like
function addElement(arr, element) {
if (arr.includes(element)) {
arr.splice(arr.indexOf(element, 1));
}
arr.unshift(element);
}
I guess this could be done with Sets, since sets can only contain unique values.
You could use a Set and delete the item in advance and add it then. To get the wanted order, you need to reverse the rendered array.
function addToSet(v, set) {
set.delete(v);
set.add(v);
}
var set = new Set;
addToSet('d', set);
addToSet('c', set);
addToSet('b', set),
addToSet('a', set);
addToSet('d', set);
console.log([...set].reverse());
var val = 'c';
var arr = ['a','b'];
if($.inArray( val, arr ) ==-1){
// value dosend exit
arr.unshift(val);
} else {
console.log('value already there')
}
console.log(arr);
$.inArray() work similar to indexOf() method. It searches the element in an array, if it’s found then it return it’s index.
http://webrewrite.com/check-value-exist-array-javascriptjquery/
your function works just you have to adjust with a small fix
arr.splice(arr.indexOf(element),1);
var arr = ['a', 'b', 'c'] ;
function addElement(arr, element) {
if (arr.includes(element)) {
arr.splice(arr.indexOf(element),1);
}
arr.unshift(element);
}
addElement(arr,'d');
addElement(arr,'b');
console.log(arr);
Especially for those who don't like .unshift() performance This would be another way of doing this job;
function funky(a,e){
var ix = a.indexOf(e);
return (~ix ? a.splice(ix,0,...a.splice(0,ix))
: a.splice(0,0,e),a);
}
var a = ['d', 'a', 'b', 'c'];
console.log(funky(a,'z'));
console.log(funky(a,'d'));
console.log(funky(a,'c'));
console.log(funky(a,'f'));

Lodash method to check whether all elements in an array are in another array

I have 2 arrays of string. I want to make sure all elements of the second array are in the first. I use Lodash/Underscore for things like this. Its easy when checking if one astring is in an array:
var arr1 = ['a', 'b', 'c', 'd'];
_.includes(arr1, 'b');
// => true
But when its an array, I cant see a current method to do it. What I've done is:
var arr1 = ['a', 'b', 'c', 'd'];
var arr2 = ['a', 'b', 'x'];
var intersection = _.intersection(arr1, arr2);
console.log('intersection is ', intersection);
if (intersection.length < arr2.length) {
console.log('no');
} else {
console.log('yes');
}
Fiddle is here. But its rather long-winded. Is there a built in Lodash method?
You could use _.xor for a symmetric difference and take the length as check. If length === 0, the both arrays contains the same elements.
var arr1 = ['a', 'b', 'c', 'd'],
arr2 = ['a', 'b', 'x'];
console.log(_.xor(arr2, arr1));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Index of the largest float in the array

How can I get the index of the largest element in the array of floats?
[0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8]
Once I get this index, I then want to get the value of another array at this index.
Let's call the second array:
['a', 'b', 'c', 'd', 'e']
When I ran the following, I got 'b' instead of 'c'.
I iterated through the first array and made a map of the floats to the strings. Then I got the string at the the first element of the first array ( array of floats ) sorted.
//aInput in the array of floats.
var emObj={};
for(var i=0; i<aInput.length; i++){
emObj[aInput[i]]=['a', 'b', 'c', 'd', 'e'][i];
}
return emObj[aInput.sort()[0]];
I also tried a method where I iterated through the array of floats and stored the largest value in a variable. Then I'd do something like this:
return ['a', 'b', 'c', 'd', 'e'][aInput.indexOf(largestFloat)];
But neither of these worked. Always returning the wrong string.
I'd suggest using Math.max() and indexOf()
var maxNum = Math.max.apply(null, aInput);
var index = aInput.indexOf(maxNum);
return ['a', 'b', 'c', 'd', 'e'][index];
An approach using Array.prototype.reduce()
This allows for arbitrary complexity in the reduce logic.
First, set up some data:
var data = [0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8];
var reference = ['a', 'b', 'c', 'd', 'e'];
Then, find the value and index of the maximum value in the array.
var result = data.reduce(function (previousValue, currentValue, index, array) {
if(previousValue.value > currentValue) {
return previousValue;
} else {
return {value: currentValue, index: index};
}
})
console.log(reference[result.index]);
Alternatively you could find the referenced value directly like this.
var result = data.reduce(function (previousValue, currentValue, index, array) {
if(previousValue.value1 > currentValue) {
return previousValue;
} else {
return {value1: currentValue, value2: reference[index]};
}
})
console.log(result);
This outputs Object {value1: 0.9573732678543363, value2: "c"}

Remove array elements and add them back to where they were

I am trying to remove elements from arrays while remembering their position and add them back later. So far I have this piece of code:
var my_array = ['A', 'B', 'C', 'D', 'E'];
var removed_elements = [];
// Assuming letter provided exists in my_array
function remove_element(letter) {
for (var index in my_array) {
if (my_array[index] == letter) {
break;
}
}
var removed_element = {
index: index,
letter: letter
}
removed_elements.push(removed_element);
my_array.splice(index,1);
}
// Assuming letter provided exists in removed_elements
function add_element(letter) {
for (var index in removed_elements) {
console.log('test');
if (removed_elements[index].letter == letter) {
console.log(removed_elements[index]);
break;
}
}
my_array.splice(removed_elements[index].index,0,removed_elements[index].letter);
}
It works fine as long as I remove 1 element at a time and add it back before removing another one. However, when I start removing several elements consecutively, the index saved for removed elements (not first one, but subsequent ones) becomes relative to the state of my_array at the time of removal, and not absolute to my_array's initial state, which can cause problems.
For instance if you remove 'B' and 'D' and add 'D' and 'B', you end up with ['A', 'B', 'C', 'E', 'D'] instead of ['A', 'B', 'C', 'D', 'E'].
Here is a jsfiddle showing what the problem is
What modifications should I change for my_array to end up in its initial state no matter of many elements I remove or add and how?
I thought about storing information about which elements surround the removed element at the time of removal and use that as extra info when adding back but wondering if there is a better way.
I wouldn't actually remove them at all:
var my_array = ['A', 'B', 'C', 'D', 'E'];
var removed = [];
function remove_element(letter) {
var i = my_array.indexOf(letter);
if(i > -1) {
removed.push(i);
}
}
function add_element(letter) {
var i = my_array.indexOf(letter);
if(i > -1) {
removed.splice(removed.indexOf(i), 1);
}
}
function get_array() {
return my_array.filter(function(x, i) {
return removed.indexOf(i) === -1;
});
}

Categories

Resources