How to simplify this delete from array jQuery - javascript

I have an object and an array of categories that should be kept in the object. This snip https://jsfiddle.net/h10rkb6s/2/ ( see log ) works but I cant seems to shake the idea that it is to complicated for a simple search and keep task.
var thz_icon_source = {"Spinners":["spinnericon1","spinnericon2"],"Awesome":["awesomeicon1","awesomeicon2"],"Others":["othericon1","othericon2"]};
var $categories = '["Spinners","Awesome"]';
var $CatsArray = JSON.parse($categories);
var groups = [];
for(var k in thz_icon_source) groups.push(k);
$.each($CatsArray,function(i,keep){
var index = groups.indexOf(keep);
if (index !== -1) {
groups.splice(index, 1);
}
});
for (var i = 0; i < groups.length; i++) {
delete thz_icon_source[groups[i]];
}
I tried with
$.each(thz_icon_source,function(category,icons){
$.each($CatsArray,function(i,keep){
var index = category.indexOf(keep);
if (index !== -1) {
delete thz_icon_source[category];
}
});
});
but this works only if 1 item is inside my search array.
Any help is appreciated.

There's no need to iterate over $CatsArray to find out which ones should be deleted. You will need to iterate over the keys of the object, and find out for each of them whether it should be deleted, to filter by that.
Leaving the top 3 lines of your script intact, you could simplify to
var keysToDelete = Object.keys(thz_icon_source).filter(function(groupName) {
return $CatsArray.indexOf(groupName) == -1;
});
($.grep would be the jQuery-ism for the filter method, if you are into that).
But assuming we don't even need those groups in an array, you could simply do
for (var groupName in thz_icon_source)
if ($CatsArray.indexOf(groupName) == -1)
delete thz_icon_source[groupName];
However, instead of deleting items from that object, I'd recommend to create a new object with only those that you want to keep. It's much easier to use:
var kept = {};
for (var i=0; i<$CatsArray.length; i++)
kept[$CatsArray[i]] = thz_icon_source[$CatsArray[i]];

Related

How can I delete array elements just once to add new ones with a for loop

What I am trying to do is:
set an array value (list) to another array (options).
If the user's input (searchVal) matches with a list value it will delete options, push this match, and then will keep pushing the next matches without deleting options again.
So according to the code below, if searchVal was "whatever", options should return: ["whatever", "whatevEver1"] but, instead, it returns: ["whatever", "WhatEver1", "whatttever", "whatever", "whatevEver1"]
Relevant code:
var list = ["whatever", "WhatEver1", "whatttever"];
var clear = 0;
var options = [];
for (var i=0 ; i < list.length ; i++)
{
options.push([list[i]]);
}
var searchVal = window.prompt(" ");
for (var i=0 ; i < list.length ; i++)
{
if (list[i].toLowerCase().includes(searchVal.toLowerCase())) {
if (clear == 0) {
options.length = 0;
}
options.push([list[i]]);
}
clear++;
}
return options;
Js arrays are pass-by-reference. In order to make independent copy of array you need to use:
let options = JSON.parse(JSON.stringify(list));
I didnt try to implement this to your problem cause im too lazy but i think it might work.

How to check each item in an array that contains a specific part of a string

function buildEVQuestionLists(category) {
var items = [];
var mySurvey = SurveyUtil.Surveys.Get(CurrentPID());
var remoteQuestions = mySurvey.Questions;
for (var i = 0; i < remoteQuestions.Count; i++) {
var question = remoteQuestions[i];
if (question.IsInCategory(category)) items.push(question.Id);
}
return items;
}
This is what return items gives:[EV10013,EV10361,EV10022,EV10009,EV10003,EV10025,EV10020,EV10017,EV10005,EV10000,EV10043,PH10040,PH10013]
Now I would like to go through this list and only return the items that start with 'EV'.
As you tagged startswith, instead of filtering the array afterwards, you could add an extra check if the string starts with EV before pushing the question id to the items array.
For example
if (question.IsInCategory(category) && question.Id.startsWith("EV")) items.push(question.Id);

Remove duplicates in array separated by double commas in JavaScript

I have an array in JavaScript like this
var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
when I alert in JavaScript it gives as below
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
But I want like this which is duplicates removed array
var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
On alert it should give like this
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
First Thing your array contains string as a constant that's not going to work.
Secondly, if all of you value are strings you can do it as follows:
var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"];
var uniqueArray = data.filter(function(item, pos) {
return data.indexOf(item) == pos;
})
alert(uniqueArray);
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:
var data [/* ... */];
var unique_data = [];
for(let i = 0; i < data.length; i++) {
if (data[i] && unique_data.indexOf(data[i]) === -1) {
unique_data.push(data[i]);
}
}
Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().
You can create your unique function to remove duplicate entry and empty value from array like this.
var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"]
var unique_data = uniqueList(data);
alert(unique_data);
function uniqueList(list) {
var uniqueResult = [];
$.each(list, function(i, e) {
if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value
uniqueResult.push(e);
});
return uniqueResult ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sorting 2D javascript array

I have an array containing a list of tags and count.
tags_array[0] = tags;
tags_array[1] = tags_count;
I need to sort the arrays base on the count so that I can pick out the top few tags.
Sort one, while storing the sort comparisons. Then sort the other using those results:
var res = [];
tags_count.sort( function( a, b ){ return res.push( a=a-b ), a; } );
tags.sort( function(){ return res.shift(); } );
Supposing tags and tags_count are 2 arrays of same length, I would first build a proper array of objects :
var array = [];
for (var i=0; i<tags_count.length; i++) {
array.push({tag:tags[i], count:tags_count[i]});
}
And then sort on the count :
array.sort(function(a, b) {return a.count-b.count});
If you need to get your arrays back after that, you may do
for (var i=0; i<array.length; i++) {
tags[i] = array[i].tag;
tags_count[i] = array[i].count;
}
Demonstration
Assuming that both tags and tags_count are arrays with the same length (that part of the question wasn't too clear), the following is one way to do the trick.
var tags_array = new Array();
for (var i = 0; i < tags.length; i++)
{
tags_array[i] = {};
tags_array[i].tagName = tags[i];
tags_array[i].tagCount = tags_count[i];
}
tags_array.sort(function(a,b){return b.tagCount-a.tagCount});
One should note that it might be possible to structure the data in this way from the start instead of rewriting it like this, in which case that is preferable. Likewise, a better structure can be used to save the data, but this will work.

unset javascript array for

I've been trying at this for hours now and I thought it would be really simple;
Using javascript I basically want to iterate through an array, get the current value of the index and then unset this value from the array. I've found splice() is supposed to work for this however I don't seem to be able to empty the array, there is always one value left on the arrary
var filtered = array("up", "down", "left");
function resetTags(){
var length = filtered.length;
for(i=0; i <= length; i++){
filtered.splice(i,1);
}
}
EDIT::
I'll try to explain in a bit more detail:
I'm basically trying to keep track of a listed of selected class values which are obtained
from when an item is clicked:
var filtered = array();
jQuery("li a").click(function () {
tag = jQuery(this).text();
addFiltered(tag);
});
function addFiltered(param){
var inArray = jQuery.inArray(param,filtered);
if(inArray > -1){
//param is in array, so we want to remove it from the filtered array
filtered.splice(index, 1);
});
}else{
//param isn't in array, so we want to add it to the array
filtered.splice(0, 0, param);
});
}
}
If you want to empty the array, set it to be an empty array directly:
filtered = [];
If you want to use the values before emptying the array, simply iterate before that without removing values and clear it when you are done.
What do you stand to gain by messing with convoluted solutions?
the array was defined incorrectly. That is why the code didn't excute
var filtered = ["up", "down", "left"];
function resetTags(){
var length = filtered.length;
for(i=0; i <= length; i++){
filtered.splice(i,1);
}
}
To remove items one by one:
var a = [1,2,3,4,5];
while (a.length > 0 ) {
a.splice(0,1);
}
http://jsfiddle.net/89hkH/
Well, you're incrementing. Have you tried decrementing?
var filtered = new Array("up", "down", "left");
function resetTags(){
var length = filtered.length;
for(i = length; i >= 0; i--){
filtered.splice(i,1);
}
}
This should make sure the final element is spliced.
I basically want to iterate through an array, get the current value
of the index and then unset this value from the array.
for(i=0; i <= length; i++){
filtered.splice(i,1);
}
I don't think you are clearly defining (or perhaps don't know), what you're trying to do.
Are you trying to write a pop(n) method such that:
var a = [1,2,3,4]
var result = pop(3, a)
result == [ 1, 2, 4]
Or are you just trying to walk an array and get the first element off every time? If so, you're doing it wrong. That's just a shift()
var filtered = ["up", "down", "left"]
for(i = 0 ; i<= filtered.length; i++)
{
alert(filtered);
filtered.shift();
alert(filtered);
}

Categories