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);
Related
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)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm solving a challenge which has a sequence of integers from 1 to N, and the task is to find the missing integer in the sequence, and the one integer that is duplicated.
The constraints -
You are not allowed to sort the array.
Your solution should not time out for large values of N.
Ideally, your solution should not use extra space except the one provided by the input array (which can be modified).
My current code times out, I'm assuming that's because the complexity for finding the duplicate element might be O(N^2).
For the missing element, my algorithm is -
Create a variable, set it to 1, and loop until condition is true
In loop, check if variable is present in array, if so, increment variable and continue loop
If variable was not found in array, this was the missing element. Break out of loop.
This should run in O(N) time, so this part should be fine.
For the duplicate element, my approach was to check the first index and last index of every element in array. For unique elements, the index values would be the same, but it would be different for the duplicates.
This is where the problem lies, I think.
My code -
function solution(array) {
var missing = 0,
duplicate = 0;
let notFound = true;
let curr = 1;
while (notFound) {
if (array.indexOf(curr) === -1) {
notFound = false;
break;
}
curr++;
}
missing = curr;
duplicate = array.find((e, i, arr) => arr.indexOf(e) !== arr.lastIndexOf(e));
return [missing, duplicate];
}
console.log(solution([2, 3, 1, 4, 4, 6]));
I checked some related questions, like this and this, but couldn't get anything out of them.
How do I fix this?
I think you can hash your input array.
What I mean by that is, suppose your array is [4,1,5,6,3,1]
Here is a simple pseudo-code.
You can get duplicate element like this:
for i:array.length
array[array[i]] = array[i]*-1 // you found and marked first element of your array
if(array[i] > 0) //it would be positive if you found and marked an element twice.
array[array[i]] is the duplicate element
This runs in O(n)
Now to get the missing element, you can traverse the array again
for i:array.length
if (array[i] > 0 && array[i]!=duplicate element) //there would be two positive numbers, missing number and the duplicate
i = missing element
This O(n) again, so its O(n) overall.
If anything is unclear, you can ask. Sorry about preferring to write a pseudo-code instead of an explanation.
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]);
});
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
So I have an array of numbers, let's say ["1", "3", "2"]
they correspond to values of the data-cardNumber attribute I've given to certain elements.
I want all elements with the data-cardNumber values in the array to be removed.
I tried doing this by iterating through the array and constructing a selector per each item in the array that calls .remove(), but that doesn't work.
I think the selector is too complex since it spans multiple strings.
How can I iterate through the array and .remove() all elements with the data-cardNumber attribute whose values are in the array?
Here is the code that I tried:
for(var i=0; i<swipedAwayCards.length; i++){
$('[data-cardNumber="'+swipedAwayCards[i]'"]').remove();
// i'm trying to construct a selector like [data-cardNumber="1"]
}
Looks like it's just a syntax error, which should have shown up in console:
$('[data-cardNumber="'+swipedAwayCards[i]+'"]')
(You missed the final + in your concatenation).
You could try the following:
$('[data-cardNumber="'+swipedAwayCards[i] + '"]').each(function() {
$(this).remove();
});
This should work rather than doing a for loop since jquery already has the capability to iterate over all matches of a selector.
You may need to do either of the the Following
var a = [1,2,3,4];
for(var i = 0 ; i< a.length; i++){
delete(a[i]); // This resets the value to undefined
}
which produces the following result
[undefined, undefined, undefined, undefined]
or
var a = [1,2,3,4];
var b;
for(var i = 0 ; i< a.length; i++){
b = a.pop();// This actually removes the Element from array and puts it in the variable b
}
Result: ** b = 1 At last as last element to be popped will be 1 and b = []**