Javascript, consolidate array elements - javascript

I'm stuck of finding a way to consolidate array elements.
so my array is in format of [id1:port1,id2:port2,id1:port3,id2:port4,id5:port5...] where each element has 2 portions. The id portion is not unique. what I try to consolidate is to create a new array will have data like [id1#port1:port3,id2#port2:port4,id5#port5]
I tried code below but it didn't get me too far. can any guru help me out?
var orinString = "id1:port1,id2:port2,id1:port3,id2:port4,id5:port5";
var newArray1 = orinString.split(",");
var newArray2 = orinString.split(",");
var newArray3 = [];
for (x=0; x<=newArray1.length-1; x++) {
for (y=0; y<= newArray2.length-1; y++) {
if ((newArray1[x].split(":")[0] == newArray2[y].split(":")[0]) && (newArray1[x].split(":")[1] != newArray2[y].split(":")[1])) {
newArray3.push(newArray1[x].split(":")[0] +"#"+ newArray1[x].split(":")[1]);
}
}
}
for (z=0; z<=newArray3.length; z++) {
gs.log("show me the result " +newArray3[z]);
}

is it that you want:
var orinString = "id1:port1,id2:port2,id1:port3,id2:port4,id5:port5";
var arr1 = orinString.split(",");
var temp= "";
var newStr = "";
arr1.sort();
for(i=0; i< arr1.length; i++) {
var item = arr1[i].split(':');
if(item[0] !== temp || temp === "") {
newStr += "," + item[0] + "#" + item[1];
} else {
newStr += ":"+item[1];
}
temp = item[0];
}
console.log(newStr.substring(1));

A typical way to solve a problem like this is
Convert them into workable values
Populate some kind of lookup table
Output the results of this lookup table
For example
var orinString = "id1:port1,id2:port2,id1:port3,id2:port4,id5:port5";
var idsAndPorts = orinString.split(",");
// Populate a key lookup
var hashTable = {};
idsAndPorts.forEach(function(s) {
var splitValue = s.split(':');
var key = splitValue[0];
var value = splitValue[1];
if(hashTable[key]) {
hashTable[key].push(value);
} else {
hashTable[key] = [value];
}
});
// Now convert it back into an array again
var finalArray = [];
for(var k in hashTable) {
finalArray.push(k + '#' + hashTable[k].join(','));
}
// View the results
finalArray.forEach(function(f) {
console.log(f);
})
This does not guarantee the final array will be sorted, but you can sort it yourself if you wish.

Related

Function to check if parameter is still the same

I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this
var data = ['test1','test1','test1','test2'];
now I will check them if the data on that array inside the loop are currently the same. for example like this.
for (var i = 0; i < data.length; i++) {
var value = data[i][0];
console.log(checkifcurrent(value));
}
my problem here is to return checkifcurrent(value) if it still the same like this
function checkifcurrent(value) {
if (currentvalue is still the same as the last one) {
console.log(same);
} else {
console.log(not same);
}
}
I hope you understand tysm for understanding
You can do it like this, no need for a function call.
var data = ['test1','test1','test1','test2'];
lastValue = data[0];
for (var i = 1; i < data.length; i++) {
var currentValue = data[i];
if(lastValue==currentValue){
console.log("Value is same")
}
else
{
console.log("Value is not same")
}
lastValue = currentValue;
}
you can iterate over the data array and compare with all the array elements except the one at the current position.
If it is equals to the current and the index is not the same of the current then it is a duplicate
var data = ['test1','test1','test1','test2'];
for (var i = 0; i < data.length; i++) {
var value = data[i];
for(var j = 0; j < data.length; j++){
//skip the index at position i, because it is the one we are currently comparing
if(i !== j && data[j] === value) {
console.log('another value like: ' + value + ' at position: ' + i + ' has been found at index: ' + j)
}
}
}
Its not very clear about your task, i hope it is checking if the a value present in arr1 is available are not in arr2. If you so,
Loop through all elements in arr1 and check the indexof it
arr1 =[1,2,3,4];
arr2 = [2,3,4,5,6,6];
arr1.forEach((x)=>{if(arr2.indexOf(x)==-1){console.log('unable to find the element'+x)}})
unable to find the element1
var isSame = (function () {
var previous;
return function(value){
var result = value === previous;
previous = value;
return result;
}
})();
Alternatively you can use lodash difference function to compare old and new array.
http://devdocs.io/lodash~4/index#difference
For example:
const _ = require('lodash')
// Save the old array somewhere
let oldArray = ['test1','test1','test1','test2']
let newArray = ['test1','test1','test1','test3']
const areParametersTheSame = !!(_.difference(oldArray, newArray))

get key value pairs out from the string javascript

If my string looks like this
"<First key="ab" value="qwerty"/>
<First key="cd" value="asdfg"/>
<First key="ef" value="zxcvb"/>"
and I want to get data out in the format
ab:"qwerty"
cd:"asdfg"
ef:"zxcvb"
How should I write the JS ?
It would be useful to see the code you've attempted, but here's a way you could achieve it:
Use a regex to pick out the relevant parts of the string.
var regex = /key="([a-zA-Z]+)" value="([0-9a-zA-Z\-\.]+)"/;
Function to remove empty elements.
var notEmpty = function (el) { return el !== ''; };
split the string into an array on the carriage return and use reduce to build the new object by applying the regex to each array element.
var out = str.split('\n').filter(notEmpty).reduce(function(p, c) {
var match = c.match(regex);
p[match[1]] = match[2];
return p;
}, {});
OUTPUT
{
"ab": "qwerty",
"cd": "asdfg",
"ef": "zxcvb"
}
DEMO
Please, make your question more clear(What result data type would you like to get?), or try these functions:
var string = '<First key="ab" value="qwerty"/><First key="cd" value="asdfg"/><First key="ef" value="zxcvb"/>'
var ParseMyString1 = function(str){
var arr = str.split(/[</>]+/); //"
//console.log(arr);
var result = [];
for (var i =0; i<arr.length; i++) {
var subStr=arr[i];
if (subStr.length!==0) {
var subArr = subStr.split(/[\s"=]+/); //"
//console.log(subArr);
var currObj = {};
var currKey = "";
var currVal = "";
for (var j =0; j<arr.length; j++) {
if (subArr[j]=="key"){
currKey = subArr[++j];
}else if (subArr[j]=="value"){
currVal = subArr[++j];
}
};
currObj[currKey] = currVal;
result.push(currObj);
};
};
console.log("ParseMyString1:");
console.log(result);
};
var ParseMyString2 = function(str){
var arr = str.split(/[</>]+/); //"
//console.log(arr);
var resultObj = {};
for (var i =0; i<arr.length; i++) {
var subStr=arr[i];
if (subStr.length!==0) {
var subArr = subStr.split(/[\s"=]+/); //"
//console.log(subArr);
var currKey = "";
var currVal = "";
for (var j =0; j<arr.length; j++) {
if (subArr[j]=="key"){
currKey = subArr[++j];
}else if (subArr[j]=="value"){
currVal = subArr[++j];
}
};
resultObj[currKey] = currVal;
};
};
console.log("ParseMyString2:");
console.log(resultObj);
};
$(document).ready(function(){
ParseMyString1(string);
ParseMyString2(string);
});
These functions return results as below (array of objects):
ParseMyString1:
[{ab:"qwerty"},{cd:"asdfg"},{ef:"zxcvb"}]
ParseMyString2:
{ab:"qwerty",cd:"asdfg",ef:"zxcvb"}
First, your string is not valid (double quotes within double quotes). You'd either need to escape the inner quotes with \" or just replace the inner quotes with single quotes.
But, assuming that your data was always going to be in the format you show, this simple code will extract the data the way you want:
var data = "<First key='ab' value='qwerty'/><First key='cd' value='asdfg'/><First key='ef' value='zxcvb'/>";
data = data.replace(/<First /g, " ").replace(/\/>/g, "").replace(/key=/g, "").replace(/value=/g, "").trim();
var ary = data.split(" ");
var iteration = "";
var result = "";
for(var i = 0; i < ary.length; i+=2){
iteration = ary[i].replace(/'/g, "") + ":" + ary[i+1].replace(/'/g, "\"");
alert(iteration);
result += " " + iteration;
}
alert("Final result: " + result);
Your input is a kind of XML. The best way is to treat it as such. We will parse it as XML, but to do so, we need to first wrap it in a root element:
var str = "<Root>" + input + "</Root>"
We parse it with
var parser = new DOMParser();
var dom = parser.parseFromString(str, "text/xml");
Get the document element (Root):
var docelt = dom.documentElement;
Now we can loop over its children and build our result, using standard DOM access interfaces like getAttribute:
var result = {};
var children = docelt.children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
result[child.getAttribute('key')] = child.getAttribute('value');
}
> result
< Object {ab: "qwerty", cd: "asdfg", ef: "zxcvb"}
You can replace the above looping logic with reduce or something else as you prefer.
This approach has the advantage that it takes advantage of the built-in parser, so we don't end up making assumptions about the syntax of XML. For instance, the regexp suggested in another answer would fail if the attributes had spaces before or after the equal sign. It would fail if the values contained Unicode characters. It would fail in odd ways if the XML was malformed. And so on.

Sort array of strings into array of objects

Okay, so I've been working on a sort function for my application, and I've gotten stuck.
Here's my fiddle.
To explain briefly, this code starts with an array of strings, serials, and an empty array, displaySerials:
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"];
var displaySerials = [];
The aim of these functions is to output displaySerials as an array of objects with two properties: beginSerial and endSerial. The way that this is intended to work is that the function loops through the array, and tries to set each compatible string in a range with each other, and then from that range create the object where beginSerial is the lowest serial number in range and endSerial is the highest in range.
To clarify, all serials in a contiguous range will have the same prefix. Once that prefix is established then the strings are broken apart from the prefix and compared and sorted numerically.
So based on that, the desired output from the array serials would be:
displaySerials = [
{ beginSerial: "BHU-008", endSerial: "BHU-011" },
{ beginSerial: "BHU-000", endSerial: "BHU-002" },
{ beginSerial: "TYU-969", endSerial: "TYU-970" }
]
I've got it mostly working on my jsfiddle, the only problem is that the function is pushing one duplicate object into the array, and I'm not sure how it is managing to pass my checks.
Any help would be greatly appreciated.
Marc's solution is correct, but I couldn't help thinking it was too much code. This is doing exactly the same thing, starting with sort(), but then using reduce() for a more elegant look.
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"]
serials.sort()
var first = serials.shift()
var ranges = [{begin: first, end: first}]
serials.reduce(mergeRange, ranges[0])
console.log(ranges) // the expected result
// and this is the reduce callback:
function mergeRange(lastRange, s)
{
var parts = s.split(/-/)
var lastParts = lastRange.end.split(/-/)
if (parts[0] === lastParts[0] && parts[1]-1 === +lastParts[1]) {
lastRange.end = s
return lastRange
} else {
var newRange = {begin: s, end: s}
ranges.push(newRange)
return newRange
}
}
I've got a feeling that it's possible to do it without sorting, by recursively merging the results obtained over small pieces of the array (compare elements two by two, then merge results two by two, and so on until you have a single result array). The code wouldn't look terribly nice, but it would scale better and could be done in parallel.
Nothing too sophisticated here, but it should do the trick. Note that I'm sorting the array from the get-go so I can reliably iterate over it.
Fiddle is here: http://jsfiddle.net/qyys9vw1/
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"];
var myNewObjectArray = [];
var sortedSerials = serials.sort();
//seed the object
var myObject = {};
var previous = sortedSerials[0];
var previousPrefix = previous.split("-")[0];
var previousValue = previous.split("-")[1];
myObject.beginSerial = previous;
myObject.endSerial = previous;
//iterate watching for breaks in the sequence
for (var i=1; i < sortedSerials.length; i++) {
var current = sortedSerials[i];
console.log(current);
var currentPrefix = current.split("-")[0];
var currentValue = current.split("-")[1];
if (currentPrefix === previousPrefix && parseInt(currentValue) === parseInt(previousValue)+1) {
//sequential value found, so update the endSerial with it
myObject.endSerial = current;
previous = current;
previousPrefix = currentPrefix;
previousValue = currentValue;
} else {
//sequence broken; push the object
console.log(currentPrefix, previousPrefix, parseInt(currentValue), parseInt(previousValue)+1);
myNewObjectArray.push(myObject);
//re-seed a new object
previous = current;
previousPrefix = currentPrefix;
previousValue = currentValue;
myObject = {};
myObject.beginSerial = current;
myObject.endSerial = current;
}
}
myNewObjectArray.push(myObject); //one final push
console.log(myNewObjectArray);
I would use underscore.js for this
var bSerialExists = _.findWhere(displaySerials, { beginSerial: displaySettings.beginSerial });
var eSerialExists = _.findWhere(displaySerials, { endSerial: displaySettings.endSerial });
if (!bSerialExists && !eSerialExists)
displaySerials.push(displaySettings);
I ended up solving my own problem because I was much closer than I thought I was. I included a final sort to get rid of duplicate objects after the initial sort was finished.
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"];
var displaySerials = [];
var mapSerialsForDisplay = function () {
var tempArray = serials;
displaySerials = [];
for (var i = 0; i < tempArray.length; i++) {
// compare current member to all other members for similarity
var currentSerial = tempArray[i];
var range = [currentSerial];
var displaySettings = {
beginSerial: currentSerial,
endSerial: ""
}
for (var j = 0; j < tempArray.length; j++) {
if (i === j) {
continue;
} else {
var stringInCommon = "";
var comparingSerial = tempArray[j];
for (var n = 0; n < currentSerial.length; n++) {
if (currentSerial[n] === comparingSerial[n]) {
stringInCommon += currentSerial[n];
continue;
} else {
var currentRemaining = currentSerial.replace(stringInCommon, "");
var comparingRemaining = comparingSerial.replace(stringInCommon, "");
if (!isNaN(currentRemaining) && !isNaN(comparingRemaining) && stringInCommon !== "") {
range = compareAndAddToRange(comparingSerial, stringInCommon, range);
displaySettings.beginSerial = range[0];
displaySettings.endSerial = range[range.length - 1];
var existsAlready = false;
for (var l = 0; l < displaySerials.length; l++) {
if (displaySerials[l].beginSerial == displaySettings.beginSerial || displaySerials[l].endSerial == displaySettings.endSerial) {
existsAlready = true;
}
}
if (!existsAlready) {
displaySerials.push(displaySettings);
}
}
}
}
}
}
}
for (var i = 0; i < displaySerials.length; i++) {
for (var j = 0; j < displaySerials.length; j++) {
if (i === j) {
continue;
} else {
if (displaySerials[i].beginSerial === displaySerials[j].beginSerial && displaySerials[i].endSerial === displaySerials[j].endSerial) {
displaySerials.splice(j, 1);
}
}
}
}
return displaySerials;
}
var compareAndAddToRange = function (candidate, commonString, arr) {
var tempArray = [];
for (var i = 0; i < arr.length; i++) {
tempArray.push({
value: arr[i],
number: parseInt(arr[i].replace(commonString, ""))
});
}
tempArray.sort(function(a, b) {
return (a.number > b.number) ? 1 : ((b.number > a.number) ? -1 : 0);
});
var newSerial = {
value: candidate,
number: candidate.replace(commonString, "")
}
if (tempArray.indexOf(newSerial) === -1) {
if (tempArray[0].number - newSerial.number === 1) {
tempArray.unshift(newSerial)
} else if (newSerial.number - tempArray[tempArray.length - 1].number === 1) {
tempArray.push(newSerial);
}
}
for (var i = 0; i < tempArray.length; i++) {
arr[i] = tempArray[i].value;
}
arr.sort();
return arr;
}
mapSerialsForDisplay();
console.log(displaySerials);
fiddle to see it work
Here's a function that does this in plain JavaScript.
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"];
function transformSerials(a) {
var result = []; //store array for result
var holder = {}; //create a temporary object
//loop the input array and group by prefix
a.forEach(function(val) {
var parts = val.split('-');
var type = parts[0];
var int = parseInt(parts[1], 10);
if (!holder[type])
holder[type] = { prefix : type, values : [] };
holder[type].values.push({ name : val, value : int });
});
//interate through the temp object and find continuous values
for(var type in holder) {
var last = null;
var groupHolder = {};
//sort the values by integer
var numbers = holder[type].values.sort(function(a,b) {
return parseInt(a.value, 10) > parseInt(b.value, 10);
});
numbers.forEach(function(value, index) {
if (!groupHolder.beginSerial)
groupHolder.beginSerial = value.name;
if (!last || value.value === last + 1) {
last = value.value;
groupHolder.endSerial = value.name;
if (index === numbers.length - 1) {
result.push(groupHolder);
}
}
else {
result.push(groupHolder);
groupHolder = {};
last = null;
}
});
}
return result;
}
console.log(transformSerials(serials));
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

javascript string conversion [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have an array
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
(This is javascript);
I don't know how to convert this array into output:
["2:6,3", "1:1,2", "3:1"];
May be you can help me?
It looks like you want to group together the elements of the list who have the same initial digit. This code will give you the associative array {"1":"1,2","2":"6,3","3ยง:"1"} as an output:
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var hist = {};
arr.map( function (a) { b=a.split(":");c=b[0]; if (c in hist) hist[c]=hist[c].concat(","+b[1]); else hist[c] = b[1]; } );
alert(JSON.stringify(hist));
See also JavaScript Group By Array
var interm = {}, output = [], regx = /(\d+):(\d+)/;
arr.forEach(function(x) {var y = regx.exec(x); if (y[1] in interm) interm[y[1]].push(y[2]); else interm[y[1]] = [y[2]]});
Object.keys(interm).map(function(x) { output.push(x + ":" + interm[x].join(',')) });
console.log(output);
[ '1:1,2', '2:6,3', '3:1' ]
That's far from the most efficient conversion in terms of speed as it uses regex and forEach, but it's fairly concise and you didn't mention that you needed anything particularly quick.
Please see this LINK..
or apply below code...
HTML Code...
<input type='button' id='s' value='test' onclick="test()"/>
JQuery code...
function test() {
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var resultStr = "";
for (i = 0; i < arr.length; i++) {
if (i <= arr.length - 2) {
var a = arr[i + 1].split(":");
if (a.length > 0) {
resultStr += arr[i] + ',' + a[1] + ' | ';
}
} else {
var str = arr[i];
resultStr += arr[i];
}
i++;
}
alert(resultStr);
}
Here is an working example on JSFiddle
And the sample code below,
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var tdarray = {};
var newarray = [];
for(var i=0;i<arr.length;i++){
var data = arr[i].split(":");
var found = false;
for(var key in tdarray){
if(data[0]==key){
found = true;
break;
}
}
var list=[];
if(found){
list = tdarray[data[0]];
}
list.push(data[1]);
tdarray[data[0]] = list;
}
for(key in tdarray){
var data = key + ":" + tdarray[key].join();
newarray.push(data);
}
console.log(newarray);
And another possible solution...
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"], alreadyUsedNumbers = [];
for (var i=0; i < arr.length; i++) {
var key = arr[i].split(":")[0], value = arr[i].split(":")[1];
if (alreadyUsedNumbers.indexOf(key) >= 0) {
for (var j=0; j < i; j++) {
if (arr[j].indexOf(key) == 0) {
arr[j] += ","+value;
arr.splice(i, 1)
i--;
break;
}
}
} else {
alreadyUsedNumbers.push(key);
}
}
console.log(arr);
... enjoy.
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1", "4:6", "3:4"];
var output = new Array();
var outputString = "[";
for(var i=0; i<arr.length; i++)
{
var index = arr[i].indexOf(":");
var firstNr = arr[i].substring(0,index);
var secondNr = arr[i].substring(index+1,arr[i].length);
var outputPart = firstNr + ":" + secondNr;
var j = i+1;
while (j<arr.length)
{
var index2 = arr[j].indexOf(":");
var firstNr2 = arr[j].substring(0,index2);
var secondNr2 = arr[j].substring(index2+1,arr[j].length);
if (firstNr == firstNr2)
{
outputPart += "," + secondNr2;
arr.splice(j,1);
}
else
j++;
}
output.push(outputPart);
}
for(var k=0; k<output.length; k++)
outputString += "'" + output[k] + "' ";
outputString += "]";
alert(outputString);
Demo here: http://jsfiddle.net/er144/QYca2/
Your output looks a lot like a map. I would write it as:
{
2 : [ 6, 3 ],
1 : [ 1, 2 ],
3 : [ 1 ]
}
To get that map, i would iterate over the array, extracting the key and value and then adding the value to the correct array, making sure to create it if it hasn't been created already.
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var map = {};
arr.forEach(function(item){
var split = item.split(':');
if (!map[split[0]]) map[split[0]] = [split[1]];
else map[split[0]].push(split[1]);
});
Obviously from my map you can get your desired array quite easily:
var result = [];
for (var key in map) {
if (map.hasOwnProperty(key)) // best practice
result.push(key+':'+map[key]);
}
console.log(result); // ["1:1,2", "2:6,3", "3:1"]
One note: it doesn't have the items in the same order you do, but that can easily be fixed by iterating over the original array to get the keys instead of using for..in:
var result = [];
arr.forEach(function(item){
var key = item.split(':')[0];
if (map[key]) {
result.push(key+':'+map[key]);
delete map[key]; // destroys the map!
}
});
console.log(result); // ["2:6,3", "1:1,2", "3:1"]
Solution 2 (no intermediate map):
This solution has O(n^2) complexity:
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var result = [];
for (var i=0; i<arr.length; i++) {
if (!arr[i]) continue;
var key = arr[i].split(':')[0];
var values = [];
for (var j=i; j<arr.length; j++) {
var split = arr[j].split(':');
if (split[0] === key) {
values.push(split[1]);
arr[j] = undefined; // destroys the original array
}
}
result.push(key + ':' + values);
}
console.log(result); // ["2:6,3", "1:1,2", "3:1"]

how can I parse json with multiple lines

I have the following JSON:
[{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}]
I need to extract all "phoneNumber" using a js function.
I'm testing from using html and my function is not so good:
function getNumbers(strJSON)
{
strJSON = "[{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557704\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557705\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557706\",\"returnCode\":\"0\"}]";
var len = strJSON.length;
var begin_index = strJSON.indexOf("returnCode") - 2;
var last_index = len - 1;
var string_toSplit = strJSON.substring(begin_index, last_index);
var string_splitted = string_toSplit.split("{");
var out="";
alert(strJSON);
alert("string_splitted");
alert(string_splitted);
for ( var i = 0; i < string_splitted.length; i++)
{
if (string_splitted[i].charAt(string_splitted[i].length - 1) === ",")
{
string_splitted[i] = string_splitted[i].slice(0, -1);
}
var json = "{" + string_splitted[i];
var obj = JSON.parse(json);
if (i == string_splitted.length)
{
out = out + obj.phoneNumber;
}
else
{
out = out + obj.phoneNumber + ",";
}
}
return out;
}
For modern browsers you can use the .map() method
var j = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phones = j.map(function(item){return item.phoneNumber});
Update
After seeing your code (do not try to manually split/parse the json string.. use the JSON.parse method) you should use
function getNumbers(strJSON)
{
var myJson = JSON.parse( strJSON );
return myJson.map(function( item ){ return item.phoneNumber}).join(',');
}
Update: An even better way:
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
return obj.map(x => x.phoneNumber).join(", ")
}
Original Post:
A straight forward method is to just iterate over every object in the array and take the values out individually.
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phoneNumbers = [];
for (var i = 0; i < info.length; i++)
{
phoneNumbers.push(info[i].phoneNumber);
}
console.log(phoneNumbers);
http://jsfiddle.net/hX69r/
UPDATE:
http://jsfiddle.net/hX69r/1/
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoString = JSON.stringify(info); //this just turns the object array 'info' into a string
var numbers = getNumbers(infoString);
console.log(numbers);
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
var phoneNumbers = [];
for (var i = 0; i < obj.length; i++)
{
phoneNumbers.push(obj[i].phoneNumber);
}
return phoneNumbers.join(", ");
}
Additional Update:
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoSingle = {"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"};
console.log(info.length); // prints 4; so you know it has the []
console.log(infoSingle.length); // prints undefined; so you know it doesn't have []
Do not try to re-invent the wheel.
There are many ways to parse JSON already:
Use JSON.parse.
Use jQuery.parseJSON

Categories