Reverse array after space using javascript - Stack Overflow

I have an array which I want to reverse like['I', ' ', 'l', 'o'

I have an array which I want to reverse like

['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];

I want to reverse it like this

["I", " ", "e", "v", "o", "l", " ", "h", "t", "r", "a", "E"]

The problem is I can reverse it using array.slice().reverse(); but it reverses the whole array and I want to reverse after where is space.

I have an array which I want to reverse like

['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];

I want to reverse it like this

["I", " ", "e", "v", "o", "l", " ", "h", "t", "r", "a", "E"]

The problem is I can reverse it using array.slice().reverse(); but it reverses the whole array and I want to reverse after where is space.

Share Improve this question edited Oct 23, 2019 at 12:32 Sebastian Kaczmarek 8,5254 gold badges24 silver badges43 bronze badges asked Apr 3, 2019 at 8:04 kumbhani bhaveshkumbhani bhavesh 2,2471 gold badge16 silver badges28 bronze badges 1
  • 3 What about splitting first on the space character, then splitting each string into chars and reversing it, then join the whole thing? – sjahan Commented Apr 3, 2019 at 8:08
Add a ment  | 

5 Answers 5

Reset to default 9

Well, some dirty solution may be similar to this one:

var sentence = ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];
    
var reversed = sentence.join('').split(' ').map(word => word.split('').reverse().join('')).join(' ').split(''); 
    
console.log(reversed);

You can make it a string, then split and flatMap

const arr = ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];

const res = arr
              .join('')
              .split(' ')
              .flatMap(e => (e + ' ').split('').reverse())
              .slice(1);

console.log(res);

You could either use the Array.reduce & Array.splice to loop through the array letter by letter (avoids creating multiple temporary arrays):

var sentence = ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];

var reversed = sentence.reduce((acc, letter) => {
    if (letter === ' ') {
        acc.result.push(letter);
        acc.insertIndex = acc.result.length;
    } else {
        acc.result.splice(acc.insertIndex, 0, letter);
    }
    return acc;
}, {result: [], insertIndex: 0});

console.log('reversed:', reversed.result);

Or use a bination of Array.join, String.split & Array.reverse (creates multiple temporary arrays):

var arr = ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];
var sentence = arr.join(''); // "I love Earth"
var words = sentence.split(' '); // [ "I", "love", "Earth" ]
var reverseParts = words.map(w => w.split('').reverse().join('')); // [ "I", "evol", "htraE" ]
var reverseSentence = reverseParts.join(' '); // "I evol htraE"
var reversed = reverseSentence.split(''); // [ "I", " ", "e", "v", "o", "l", " ", "h", "t", "r", "a", "E" ]
console.log(reversed);

Certain lines could be bined, to make it shorter and still quite clear:

var arr = ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];
var words = arr.join('').split(' '); // [ "I", "love", "Earth" ]
var reverseParts = words.map(w => w.split('').reverse().join('')); // [ "I", "evol", "htraE" ]
var reversed = reverseParts.join(' ').split(''); // [ "I", " ", "e", "v", "o", "l", " ", "h", "t", "r", "a", "E" ]
console.log(reversed);

You could take a recursive approach and collect sub arrays and reverse this values.

function swap(array, i = 0, temp = []) {
    if (i >= array.length || array[i] === ' ') {
       temp.forEach((v, j) => array[i - j - 1] = v);
       temp = [];
    } else {
        temp.push(array[i]);
    }
    if (i >= array.length) return array;
    return swap(array, i + 1, temp);
}

var array = ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];

console.log(swap(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another approach by changing the value on the way back.

function swap(array, i = 0, temp = []) {
    if (i >= array.length) return array;        
    swap(array, i + 1, array[i] === ' ' ? temp = [] : (temp.push(array[i]), temp));
    if (temp.length) array[i] = temp.shift();
    return array;
}

var array = ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];

console.log(swap(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }

// without using extra array and any predefined methods
const reverseWords = (input = []) => {
    if(input.length === 0) {
        return [];
    }
    let j = 0;
    for(let i = 0; i < input.length; i++) {
        if(i == input.length - 1 || input[i] == " ") {
            let k = 0;
            let b = input[i] == " " ? 1: 0;
            while(j > k) {
                const temp = input[i - k - b];
                input [i - k - b] = input[i-j];
                input[i-j] = temp;
                j = j -1;
                k = k+1;
            }
            j = 0;
        }else{
            j = j +1;
        }
    }
    return input;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745312987a4622085.html

相关推荐

  • Reverse array after space using javascript - Stack Overflow

    I have an array which I want to reverse like['I', ' ', 'l', 'o'

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信