Javascript array with values [closed] - javascript

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)

Related

Why is this code giving me an output of 5? [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 last year.
Improve this question
The goal of this code is to double each number in the array. I was trying to mimic the map() method. But that is not important. What I am wondering is why this code gives me an output of 5 while I did not console.log it. Then when I run it again it keeps adding 5 to a variable I am not aware of?
const numbers = [1, 2, 3, 4, 5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i += 1) {
doubleNumbers.push(numbers[i] * 2)
}
It is because Array.push returns the new length of the array:
let arr = [];
console.log(arr.push('something')) // Should output 1
console.log(arr.push('something else')) // Should output 2
You didn't log anything, but if you run code in the console it will print the outcome of the last statement.
From the documentation: the push() method adds one or more elements to the end of an array and returns the new length of the array.
If you run this in the developer console, it will log the last returned result.
Your Code output is okay
const numbers = [1,2,3,4,5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i+=1) {
doubleNumbers.push(numbers[i] * 2)
}
console.log(doubleNumbers)
Maybe You console the length of array
Maybe you aren't giving the entire context here?
What is numbers2 anyway? You declare a new array, doubleNumbers, but don't use it?
doubleNumbers.push(numbers[i] * 2)
should work just fine I believe.

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);

fetch first element of every string in array using javascript [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 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]);
});

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