how to split this complex json array? - javascript

I have an array like
["1-India","2-xxx","3-yyyy"]
I want array like
["India","xxxx"]
Please help me to get this functionality.

You can use combination of .map() and .split().
var newArr = ["1-India","2-xxx","3-yyyy"].map(x=> x.split('-')[1]);
console.log(newArr)

As I said in my comment. That what you have there, is not an JSON, it's an array. I think this could be an easy way to achieve what you want:
var arr = ["1-India", "2-xxx", "3-yyyy"];
var newArray = [];
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].replace(/[0-9-]/g, '');
newArray.push(arr[i]);
}
console.log(newArray)

Related

How do I sort my javascript array by its element which are nested inside?

Here is my array:
var myarray=[
["abc",1,**3**],
["def",2,**1**],
["ijh",0,**5**],
["abc",0,**5**]
];
Now i want to Sort the Array on the basis of values at the second element of each position. Have a look at the position of the highlight values.
How can i do it?
Have you tried using a basic bubble sort algorithm?
for(var i = 0; i < myarray.length; i++) {
if (myarray[i][1] > myarray[i+1][1]) {
var tmp = myarray[i];
myarray[i] = myarray[i+1];
myarray[i+1] = tmp;
}
}
I have try this code at my end it's working fine, Please try this one
var myarray=[
["abc",1,'**3**'],
["def",2,'**1**'],
["ijh",0,'**5**'],
["abc",0,'**5**']
];
console.log(myarray);
myarray.sort(function(a, b){
return b[1]-a[1]
})
console.log(myarray);
You can see the example here https://jsfiddle.net/ob5cd4fh/
If you want to have it sorted in ascending order, define a comparison function like the following
myarray.sort(function (item1, item2) { return item1[2] - item2[2]; });

Javascript: Convert Array to Object

Which is the easiest way to convert this:
[{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}]
to this:
{src:"websrv1", dst:"websrv2", dstport:"80"}
in order to pass it to AJAX data?
I'm using VisualSearch and it returns an array of Facet model instances which i need to convert into an Object.
var a = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var b = a.reduce(
function(reduced,next){
Object.keys(next).forEach(function(key){reduced[key]=next[key];});
return reduced;
}
);
//b should be {src:"websrv1", dst:"websrv2", dstport:"80"}
think about the array.reduce function everytime you need to perform these kind of transformations.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
If you are using jquery, try this:
var array = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}]
var arrayObj = {};
for(var i in array) {
$.extend(arrayObj, array[i]);
}
Use .reduce().
var result = data.reduce(function(obj, item) {
for (var key in item)
obj[key] = item[key];
return obj;
}, {});
Don't use this! but just for fun
var a = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var f = a.reduce((c,d) => Object.assign(c,d), {})
The tiny drawback is that a is mutated with an infinite recursive object but, who cares? it works in one line!
My 2cents, very easy to read:
var myObj = {};
myArray.forEach(function(obj) {
var prop = Object.keys(obj)[0];
myObj[prop] = obj[prop];
})
Original answer using only the most basic features of JavaScript:
var input = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var output = {};
for (var i = 0; i < input.length; i++) {
for (var n in input[i]) {
output[n] = input[i][n];
}
}
console.log(output);
UPDATE: Using newer features of JavaScript, you can do this trivially with Object.assign and spread syntax (...):
var input = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var output = Object.assign({}, ...input);
console.log(output);
Also, Object.assign(...input) will return the same result, but will modify the first element of the input array. As long as you don't mind that side effect, I'd use this simpler version.

Removing the elements from one multidimensional array from another multidimensional array

I'm finding it difficult getting my head around what I think is a pretty simple task. My brain is just fried at the moment and I have a deadline. :(
I need to take all the element arrays from one multidimensional array and remove them from another multidimensional array.
Arr1 = [["Tom", "161"], ["Dick", "29"], ["Harry", "46"], ["Mike", "72"], ["Sally", "11"]];
Arr2 = [["Harry", "46"], ["Mike", "72"], ["Tom", "161"]];
So in this instance I want to take all the element arrays from Arr2 and remove them from Arr1 so that afterward Arr1 would look like this:
Arr1 = [["Dick", "29"], ["Sally", "11"]];
Does that make sense?
EDITx2: Wait, no, ignore that, I was being stupid.
Assuming you always have two elements in the array, and a "unique" element is defined as a combination of the name and the number, you can do something like this:
function(array1, array2) {
var seen = {};
var returnedArray = [];
for(var i = 0; i < array2.length; i++) {
var elements = array2[i];
seen[elements[0] + elements[1]] = true;
//an alternative to the above is to do
//seen[JSON.stringify(elements)] = true;
}
for(var i = 0; i < array1.length; i++) {
var elements = array1[i];
if(!seen[elements[0] + elements[1]]) {
returnedArray.push(elements);
}
//an alternative to the above is to do
//if(!seen[JSON.stringify(elements)]) {
// ...
//}
//
//if you took the alternate approach in the first loop
}
return returnedArray;
}
Since it's all strings you could get creative with string methods and chaining. Probably not the best performance and a bit tricky, but it works:
var arr = [["Tom", "161"], ["Dick", "29"], ["Harry", "46"], ["Mike", "72"], ["Sally", "11"]];
var remove = [["Harry", "46"], ["Mike", "72"], ["Tom", "161"]];
var result = arr
.join('|')
.replace(RegExp(remove.join('|'),'g'),'')
.match(/[^|]+/g)
.map(function(s){ return s.split(',') });
console.log(result); //=> [["Dick","29"],["Sally","11"]]
You could even try using JSON. I wouldn't recommend this for production in any case, just for fun.
Demo: http://jsbin.com/obokuy/1/edit
If you need to put together something quick, then use a nested loop to walk through the elements of Arr2 for each element in Arr1 and do a comparison on each. You can look at the answers to this question for a hint on comparing the inner arrays:
How to check if two arrays are equal with JavaScript?

concat empty / single item array

Ok, so I have this simple code :
for(var i=0; i<lines.length; i++) {
elements += myFunction(lines[i]);
}
Where elements is an empty array at the start and myFunction() is just a function that returns an array of strings.
The problem is that if myFunction() returns an array with a single string, the += is interpreted as a string concat in place of an array concat.
At the end of the loop the result is just a long string and not an array.
I tried push()ing the values in place of concatenation, but this just gives me a two dimensional matrix with single item arrays.
How can I solve this typecasting problem ? Thank you in advance !
Try :
for(var i=0; i<lines.length; i++) {
elements [i] = myFunction(lines[i]);
}
I suppose it solves the problem.
You can use the Array concat function:
elements = elements.concat(myFunction(lines[i]));
Presumably you want something like:
var arrs = [[0],[1,2],[3,4,5],[6]];
var result = [];
for (var i=0, iLen=arrs.length; i<iLen; i++) {
result = result.concat(arrs[i]);
}
alert(result); // 0,1,2,3,4,5,6
Ah, you want to concatenate the results of a function. Same concept, see other answers.
You can also use myArray[myArray.length] = someValue;
let newArray = [].concat(singleElementOrArray)

What's wrong with this code? I try to create multiple arrays in a loop

I try to create multiple arrays in a loop. I was told that the correct way to do this is by creating 2-dimentional arrays. So I made the following code, but it keep telling me eleArray[0] is undefined. anyone? Thanks
var eleArray = [];
for(var i=0;i<rssArray;i++)
{
eleArray[i] = [];
}
eleArray[0][0] = "tester";
alert(eleArray[0][0]);
Assuming that rssArray is an array as the name implies, you need to loop based on the length:
for(var i=0;i<rssArray.length;i++)
Is the rssArray variable being initialized correctly?
Here's a working example of your question.
jsfiddle
var array = [], length = 10, i;
for(i = 0; i < length; i++){
array[i] = [];
}
array[0][0] = "Hello, World!";
document.getElementById("output").innerHTML = array[0][0];

Categories

Resources