fetch first element of every string in array using javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have an array like :
["ds","1:0,1,2,3,4","2:0,2,3,4,5","3:0,6,7,8,9"]
I want to fetch elements such that it has:
[1:0,2:0,3:0] (only the first element of every string in array leaving the ds element)
Please suggest a solution in JavaScript.

Use a forEach to loop through the array and split using ','.
var arr = ["ds", "1:0,1,2,3,4", "2:0,2,3,4,5", "3:0,6,7,8,9"];
var newArr = [];
arr.forEach(function(el,index) {
if(index!=0)
newArr.push(el.split(',')[0]);
});
console.log(newArr)

You can use the array .reduce() method:
var input = ["ds","1:0,1,2,3,4","2:0,2,3,4,5","3:0,6,7,8,9"]
var output = input.reduce(function(acc, str) {
var val = str.match(/^\d+:\d+/)
if (val) acc.push(val[0])
return acc
}, [])
console.log(output)
When processing each element you could say if (str != "ds") or skip the first element based on its index, and then use str.split(",")[0] or some combination of .slice() or .substr() and .indexOf() or whatever, but I've chosen to use a regex /^\d+:\d+/ with the .match() method to check if each input element contains the digits:digits structure at the beginning - that way it really doesn't matter what order the elements are in or what other arbitrary values might exist, it only uses elements that match the required pattern.

var arr = ["ds","1:0,1,2,3,4","2:0,2,3,4,5","3:0,6,7,8,9"];
var newArr = arr.slice(1, arr.length).map(function (el) {
return el.split(',')[0];
});
console.log(newArr);

var newarray = [];
oldarray.splice(0,1);
oldarray.forEach(function (element) {
newarray.push(element.split(",")[0]);
});

Related

Javascript array with values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The below code is a javascript interview question. I should get the output as [5,1,2,3,4]. Anyone can help me out this.
const input = [1,2,3,4,5]
const n = 4;
var output = []
console.log(output)
Without modifying the input array:
const input = [1,2,3,4,5]
const n = 4;
var output = []
output= [input[n],input.slice(0,n)].flat()
console.log(output)
From my understanding, the question is that when 'n' is a given index, you should be able to remove the element from the index n of the array and insert it at the very beginning of the array. As arrays are 0 based, it means that if n=4, then the element at nth index is 5 as per the given array.
In order to do that, you can do the following:
Use the splice method on the nth index and pass 1 as 2nd parameter, so you only remove the element at nth index.
Then use the unshift method on input to remove add the nth element at the beginning of the array. Unshift returns the length of the array, but you want the entire array to be stored in output.
So, you store the input array in the output variable.
Please run the below snippet for a better understanding. Let me know if my understanding of your question is not correct, so I can update my answer accordingly.
const input = [1,2,3,4,5]
const n = 4;
const [el] = input.splice(n,1); //array destructuring
input.unshift(el);
const output = input;
console.log(output)
const input = [1,2,3,4,5]
const n = 4
input.splice(0, 0, input[n])
input.splice(n+1, 1)
var output = [...input]
console.log(output)

Insert string into string on a dynamic position [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a string that includes some color tags, that looks like this:
[GREEN][BLUE][RED]
The position of the tags can be different. So [GREEN] could be in middle or in the last position as well.
Now I have a new color tag that should be added to that list, let's call it [YELLOW]. So [YELLOW] has a dynamic position number, let's take the variable const position = 2. Well, that means that [YELLOW] should be placed in second place, which should look like this:
[GREEN][YELLOW][BLUE][RED]
How can I do this?
const text = "[GREEN][BLUE][RED]";
const inputNumber = 2;
const addingText = "[YELLOW]";
const index = text.split("[", inputNumber).join("[").length;
const output = [text.slice(0, index), addingText, text.slice(index)].join('');
console.log(output)
I would have an array of placeholders like this:
const placeholders = ['[GREEN]', '[YELLOW]', '[BLUE]', '[RED]'];
When you need to add another placeholder in a certain position you simply use the splice function:
placeholder.splice(position, 0, newPlaceholder);
Then when you need to use it, you just convert it to a string:
placeholder.join('');
I think this would make it much easier to handle, more readable and possibly quicker too.
You could use .replace function with the following regex.
((?:\[.*?\]){2})
When you insert variable to regex using${variable}, you use:
((?:\\[.*?\\]){${position-1}})
var listColors = "[GREEN][BLUE][RED]";
const position = 2;
var color = "[YELLOW]";
var pattern = `((?:\\[.*?\\]){${position-1}})`;
var regex = new RegExp(pattern);
var newListColors = listColors.replace(regex, `$1${color}`);
console.log(newListColors);
I would split this to array and then add at specific position:
var text = "[GREEN][BLUE][RED]";
var matches = text.match(/\[\w+\]/g);
matches.splice(1, 0, "[YELLOW]");
var result = matches.join("")
console.log(result);
https://www.w3schools.com/jsref/jsref_splice.asp
You should find in which possition the first ] appears and then concat the [yellow]

Find unique prefix and remove from array of string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
In Javascript, given an array of strings, how to find the unique prefix of all the strings and then remove that prefix from each string.
For example:
["05098701", "05012302", "0545621", "0509301"]
unique prefix would be "05"
resultant array would be
["098701", "012302", "45621", "09301"]
You need to search like a human does: check with one char, then with two and so on..
Then just remove the prefix from every item from the array.
You can do this using map method by passing a callback function.
array = ["05098701", "05012302", "0545621", "0509301"]
function longestCommonPrefix(arr){
// sort() method arranges array elements alphabetically
var sortArr = arr.sort();
// Get first array element
var arrFirstElem = arr[0];
// Get the last array element length minus one
var arrLastElem = sortArr[sortArr.length - 1];
// Get first array element length
var arrFirstElemLength = arrFirstElem.length;
// Set "i" incrementer to 0
var i= 0;
// while "i" is less than the length of the first array element AND
// the first array element character position matches the last array character position
// increment "i" by one
while(i < arrFirstElemLength && arrFirstElem.charAt(i) === arrLastElem.charAt(i)) {
i++;
}
//return the prefix
return arrFirstElem.substring(0, i);
}
prefix = longestCommonPrefix(array);
array = array.map(function(item){
return item.substring(prefix.length, item.length);
});
console.log(array);

iterate though JSON array in p5.js [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 days ago.
Improve this question
I have a server that returns :
I want to iterate through this data in p5.js
var ms = []
function preload() {
var url ='https://dest/url'
ms = loadJSON(url)
}
Which I expected to return an array but it does not seem to return anything sensible.
However, if I paste the same data into the Javascript console I get different data :
How do I either iterate over this data (it is NOT loaded as an array) or convert it to an array?
I think you mean this:
var array;
for (var key in ms) {
if (!array) {
array = [a[key]];
} else {
array.push(a[key]);
}
}
console.log(array); // [ {'time': .... }, {...}, .. ]
You are getting an array of objects, Here's how you can simply iterate them
var data = [{"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"} ];
for(obj of data){
console.log("time and rate: ", obj.time, obj.rate)
}
jettpleyn had the only answer that actually worked in P5.
Eventually though - it dawned on me that I could make my life easier by changing the JSON returned from the server to an object containing an array rather than an array directly
{ "data":
[{"time":"85579.54189181328","rate":177.66287},{"time":"81978.61475682259","rate":177.66287},{"time":"78377.54175782204","rate":177.66287},{"time":"74776.58741879463","rate":177.66287},{"time":"71175.57481980324","rate":177.66287},{"time":"67574.59330582619","rate":177.66287},{"time":"63973.427922964096","rate":177.66287},{"time":"60372.39295697212","rate":177.66287},{"time":"56771.37366294861","rate":177.66287},{"time":"53170.276379823685","rate":177.66287},{"time":"49569.180530786514","rate":177.66287},{"time":"45968.02240085602","rate":177.66287},{"time":"42365.825628995895","rate":177.66287},{"time":"38764.64792180061","rate":177.71416},{"time":"35163.241872787476","rate":177.71416},{"time":"31562.00651884079","rate":177.72556},{"time":"27960.898827791214","rate":177.73126},{"time":"24359.687824964523","rate":177.67998},{"time":"20758.03328180313","rate":177.67998},{"time":"17156.808887004852","rate":174.53839},{"time":"13555.605601787567","rate":174.9276},{"time":"9954.546007871628","rate":175.35431},{"time":"6353.40945982933","rate":175.96582},{"time":"2752.3464789390564","rate":175.84541}]
}
As others have pointed out in the comments, what you have is essentially an array or an array-like object to be more precise and these can easily be converted to a proper array like so:
ms.length = Object.keys(ms).length;
var msArray = Array.prototype.slice.call(ms);
Looing at an issue in the p5.js github about this problem, more than one person suggest to do Object.values(ms) to transform the object into an array.
It has to be done after the preload function.

Object Obect array Json.stringify string array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I had a object object array which i used JSON.stringify() on i can now see what's in my array but when i do arr[0] etc it only outputs one letter.
arr = {"hello":"yes","because":"no"}
arr[0] =h
I want it to output the whole of the value not just the first letter
My code
var clientContext = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
MyProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(MyProperties);
clientContext.executeQueryAsync(getMyNewsChoicesSuccess, getMyNewsChoicesFail);
},
getMyNewsChoicesSuccess = function () {
//get the news choice by actually fieldname
var MyChoices = JSON.stringify(MyProperties.get_userProfileProperties().Value);
$('#NBStest').text(MyChoices);
},
You can get the first element from your json string like this
JSON.parse(json_str)[0]
but in the example you have, the first element is "yes" and its index is "hello" , which means you can't get the first element by the index 0 , however you can get it by its property name like this
arr.hello = "yes";
// or
arr['hello'] = "yes";
if you want to get the hello which is the key , you have to use this loop
for (key in arr)
console.log(key);
// it will print 'hello' and then 'because'
Well its not an array anymore, its a string. arr[0] will return the first letter.
If you want to get the objects from it you need to parse it ( try JSON.parse )
JSON.stringify() does exactly what it sounds like. It turns the javascript object into a string. So when you do arr[0] you are getting the first letter in the string. You need to turn it back into a javascript object if you want to get the actual values.

Categories

Resources