How to splice the string value so the output only become 'LA1','LA4'. I tried the method below but it still gave me string_2 output.
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
const index = unique_2.indexOf(unique_1);
if (index > -1) {
unique_2.splice(index, 1);
}
console.log(unique_2);
Instead of using splice() You can filter() with includes().
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
var filtered = unique_2.filter(s => !unique_1.includes(s))
console.log(filtered);
If your lists are very large, you might want to use something other than an array with includes() such as a Set that offers constant time lookups.
Array.prototype.indexOf() only finds one element and can not find an array.
To get the expected value, you can do as follows.
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
unique_2 = unique_2.filter(item => !unique_1.includes(item));
console.log(unique_2);
using reduce:
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
const result = unique_2.reduce((acc, item) => {
!string_1.includes(item) && acc.push(item)
return acc
}, [])
console.log(result)
Related
var replaceArr = ['A','J','Q',10,2];
var originalArr = [{A:0},{2:1},{3:2},{4:3},{5:4},{6:5},{10:9},{J:10},{Q:11},{K:12}];
As per the snippet I have two array:
replaceArr and originalArr
I want to compare the replaceArr with the originalArr and get the key value from there and replace into the replaceArr.
Means after replacing the replaceArr would be == [0,10,11,9,1]
In Advanced Thanks..
you can simple use map and find from array prototype
var replaceArr = ["A", "J","Q",10,2]
var originalArr = [{A:0},{2:1},{3:2},{4:3},{5:4},{6:5},{10:9},{J:10},{Q:11},{K:12}];
replaceArr = replaceArr.map(v => originalArr.find(obj => obj[v] !== undefined)[v]);
console.log(replaceArr);
You can club all the different objects in originalArr and then search for replaceArr values in it like below
var replaceArr = ['A','J','Q',10,2]
var originalArr = [{A:0},{2:1},{3:2},{4:3},{5:4},{6:5},{10:9},{J:10},{Q:11},{K:12}]
let arrWithOneObject = Object.assign(...originalArr)
let result = replaceArr.map(d => arrWithOneObject[d])
console.log(result)
You can use javascript array foreach function
originalArr.forEach((val) => {
var replaceIndex = replaceArr.indexOf(Object.keys(val)[0]);
if (replaceIndex >= 0) {
replaceArr[replaceIndex] = val[Object.keys(val)[0]];
}
});
var replaceArr = ['A','J','Q','10','2']
var originalArr = [{A:0},{2:1},{3:2},{4:3},{5:4},{6:5},{10:9},{J:10},{Q:11},{K:12}]
originalArr.forEach((item)=>{
let property = Object.keys(item)[0];
let indexOfproperty = replaceArr.indexOf(property);
if(indexOfproperty !== -1){
replaceArr[indexOfproperty] = item[property]
}
})
console.log(replaceArr)
I have two array objects as below:
var arrayOne = [{"Name":"job","SubscriptionGUID":"8ead7edfa460"},{"Name":"TestJobSQL","SubscriptionGUID":"09e7dbff7779"}];
var arrayTwo = [{"UserSubscriptionID":13,"SubscriptionGUID":"8ead7edfa460","Name":"job"}];
var arrayDiff = [];
I need to compare the element Name and remove matched element only show not matching array element in arrayDiff
as per above example My new arrayDiff should be
var arrayDiff = [{"Name":"TestJobSQL"}]; or var arrayDiff = ['TestJobSQL'];
if the arrayTwo is
var arrayTwo = [];
then arrayDiff should return
var arrayDiff = [{"Name":"TestJobSQL"},{"Name":"Job"}]; or var arrayDiff = ['TestJobSQL', 'Job'];
Try this
var arrayOne = [{"Name":"job","SubscriptionGUID":"8ead7edfa460"},{"Name":"TestJobSQL","SubscriptionGUID":"09e7dbff7779"}];
var arrayTwo = [{"UserSubscriptionID":13,"SubscriptionGUID":"8ead7edfa460","Name":"job"}];
var arrayDiff = [];
arrayOne.forEach(function(item, index){
var found = false;
arrayTwo.forEach(function(item1, index1){
if(item.Name == item1.Name) {
found = true;
}
})
if(found == false) {
arrayDiff.push({ Name : item.Name});
}
})
console.log(arrayDiff);
An easy way would be using lodash's and _.differenceBy method.
It let's you make two arrays diff based on the property you want.
var createDiffArray = function(attrName,arrayOne,arrayTwo){
var arrayDif = [];
for (let element of arrayOne){
if (arrayTwo.find( x => x[attrName] === element[attrName]) !== undefined){
arrayDif.push(element[attrName]);
}
}
return arrayDif;
}
var arrayOne = [{"Name":"job","SubscriptionGUID":"8ead7edfa460"},{"Name":"TestJobSQL","SubscriptionGUID":"09e7dbff7779"}];
var arrayTwo = [{"UserSubscriptionID":13,"SubscriptionGUID":"8ead7edfa460","Name":"job"}];
//arrayTwo=[];
var result = [];
arrayOne.forEach(function(e){
if(arrayTwo.length==0){
result.push(e.Name);
}else{
arrayTwo.forEach(function(e2){
if(e.Name!=e2.Name){
result.push(e.Name);
}
})
}
})
console.log(result);
How i Remove duplicates from my string
var string="1,2,3,2,4,5,4,5,6,7,6";
But i want like this
var string="1,2,3,4,5,6,7";
Yes you can do it easily, Here is the working example
data = "1,2,3,2,4,5,4,5,6,7,6";
arr = $.unique(data.split(','));
data = arr.join(",");
console.log(data);
Create the following prototype and use it to remove duplicates from any array.
Array.prototype.unique = function () {
var arrVal = this;
var uniqueArr = [];
for (var i = arrVal.length; i--; ) {
var val = arrVal[i];
if ($.inArray(val, uniqueArr) === -1) {
uniqueArr.unshift(val);
}
}
return uniqueArr;
}
Ex:
var str = "1,6,7,7,8,9";
var array1 = str.split(',');
var array1 = array1.unique();
console.log(array1); // [1,6,7,8,9]
str = array1.join();
Use the following to push unique values into a new array.
var names = [1,2,2,3,4,5,6];
var newNames = [];
$.each(names, function(index, value) {
if($.inArray(value, newNames) === -1)
newNames.push(value);
});
I want to split an array that already have been split.
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(',');
var array_s = array_dt.split('|');
console.log(array_s);
That code returns TypeError: array_dt.split is not a function.
I'm guessing that split() can not split an array. Have I wrong?
Here's how I want it to look like. For array_dt: 2016-08-08,2016-08-07,2016-08-06,2016-08-05,2016-08-04. For array_s: 63,67,64,53,63. I will use both variables to a chart (line) so I can print out the dates for the numbers. My code is just as example!
How can I accomplish this?
Demo
If you want to split on both characters, just use a regular expression
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(/[,|]/);
console.log(array_dt)
This will give you an array with alternating values, if you wanted to split it up you can do
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(/[,|]/);
var array1 = array_dt.filter( (x,i) => (i%2===0));
var array2 = array_dt.filter( (x,i) => (i%2!==0));
console.log(array1, array2)
Or if you want to do everything in one go, you could reduce the values to an object
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array = string.split(/[,|]/).reduce(function(a,b,i) {
return a[i%2===0 ? 'dates' : 'numbers'].push(b), a;
}, {numbers:[], dates:[]});
console.log(array)
If performance is important, you'd revert to old-school loops, and two arrays
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array = string.split(/[,|]/);
var array1 = [];
var array2 = [];
for (var i = array.length; i--;) {
if (i % 2 === 0) {
array1.push(array[i]);
} else {
array2.push(array[i]);
}
}
console.log(array1, array2)
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = [];
var array_s = [];
string.split('|').forEach(function(el){
var temp = el.split(",");
array_dt.push(temp[0]);
array_s.push(temp[1]);
});
console.log(array_dt);
console.log(array_s);
Just do it one step at a time - split by pipes first, leaving you with items that look like 2016-08-08,63. Then for each one of those, split by comma, and insert the values into your two output arrays.
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var arr = string.split("|");
var array_dt = [];
var array_s = [];
arr.forEach(function(item) {
var x = item.split(",");
array_dt.push(x[0]);
array_s.push(x[1]);
});
I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?
myData = '[data attr1="value1" attr2="value2" attr3="value3"]';
and get result array :
var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...
This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].
Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.
function decode(tag)
{
var r = /(\w+)="([^"]*)"/g,
h = {};
while ((m = r.exec(tag)) !== null) {
h[m[1]] = m[2];
}
return h;
}
Since you have string key in the data, use jquery object instead of array.
var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
var x = str_arr[val].split('=');
arr[x[0]] = x[1].replace('"','').slice(0,-1);
});
console.log(arr);
Try this code. It may help you.
Here is the DEMO
Though it can be more optimized if you put some more details about your code.
var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;
function parse(text) {
var result = [];
tagRe.lastIndex = 0; // reset start position
var tagMatch = tagRe.exec(text);
while (tagMatch) {
var currentTag = { 'name': tagMatch[1], 'attrs': {} };
var attrString = tagMatch[2];
attrRe.lastIndex = 0;
var attrMatch = attrRe.exec(attrString);
while (attrMatch) {
var attrName = attrMatch[1];
var attrValue = attrMatch[2];
currentTag.attrs[attrName] = attrValue;
attrMatch = attrRe.exec(attrString); // next match
}
result.push(currentTag);
tagMatch = tagRe.exec(text);
}
return result;
}
parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]
This works for any number of tags in the string. The name of the tag does not matter.