Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

다른 배열 JavaScript를 기반으로 배열 수정

<시간/>

다음과 같은 구문의 참조 배열이 있다고 가정합니다. -

const reference = ["your", "majesty", "they", "are", "ready"];

그리고 다른 배열을 기반으로 위 배열의 일부 요소를 결합해야 하므로 다른 배열이 다음과 같을 경우 -

const another = ["your", "they are"];

결과는 다음과 같습니다 -

result = ["your", "majesty", "they are", "ready"];

여기서는 두 배열의 요소를 비교하고 첫 번째 배열의 요소가 두 번째 배열에 함께 존재하는 경우 결합했습니다.

우리는 그러한 두 개의 배열을 취하고 새로운 결합된 배열을 반환하는 JavaScript 함수를 작성해야 합니다.

예시

const reference = ["your", "majesty", "they", "are", "ready"];
const another = ["your", "they are"];
const joinByReference = (reference = [], another = []) => {
   const res = [];
   const filtered = another.filter(a => a.split(" ").length > 1);
   while(filtered.length) {
      let anoWords = filtered.shift();
      let len = anoWords.split(" ").length;
      while(reference.length>len) {
         let refWords = reference.slice(0,len).join(" ");
         if (refWords == anoWords) {
            res.push(refWords);
            reference = reference.slice(len,reference.length);
            break;
         };
         res.push(reference.shift());
      };
   };
   return [...res, ...reference];
};
console.log(joinByReference(reference, another));

출력

이것은 다음과 같은 출력을 생성합니다 -

[ 'your', 'majesty', 'they are', 'ready' ]